02给女朋友讲讲Redis-SpringBoot集成Redis

2021-07-02  本文已影响0人  XueFengDong

一、SpringBoot集成Redis

1.引入依赖
根据SpringBoot的版本引入对应的依赖,本文采用版本为2.4.5

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 如果不引入此依赖,项目启动连接redis会报错,错误信息如下-->
          <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>    
//没有引入commons-pool2依赖报错
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig

说明:在SpringBoot2.x之后,原来依赖中使用的jedis被替换成了lettuce?

jedis:采用的直连方式,多线程操作时,是不安全的。如果想要避免不安全,使用jedis pool连接池,比较繁琐。更像BIO模式

lettuce:采用netty,实例可以在多个线程中共享,不存在线程不安全的情况。可以减少线程数据,性能更高。更像NIO模式
2.添加配置

/**
 * {@link EnableAutoConfiguration Auto-configuration} for Spring Data's Redis support.
 *
 * @author Dave Syer
 * @author Andy Wilkinson
 * @author Christian Dupuis
 * @author Christoph Strobl
 * @author Phillip Webb
 * @author Eddú Meléndez
 * @author Stephane Nicoll
 * @author Marco Aust
 * @author Mark Paluch
 * @since 1.0.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class) //此处绑定为对应的配置内容,所有的配置信息都在此类中
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}
spring:
  redis:
    # redis所在服务器ip
    host: 192.168.225.132
    # redis服务的端口号
    port: 6379
    # redis链接密码,没有可忽略不填
    password:
    # 使用的数据库 Redis默认使用db0
    database: 0
    # 连接池最大连接数
    lettuce:
      pool:
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 20
        # 连接池中的最小空闲连接
        min-idle: 2
        # 连接池中的最大空闲连接
        max-idle: 3
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
      # 在关闭客户端连接之前等待任务处理完成的最长时间,在这之后,无论任务是否执行完成,都会被执行器关闭,默认100m
      shutdown-timeout: 100
  cache:
    redis:
      # redis是否缓存空值
      cache-null-values: true

3.自定义RedisTemplate模板操作类

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        // 值采用json序列化
        template.setValueSerializer(RedisSerializer.json());
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(RedisSerializer.json());
        template.afterPropertiesSet();

        return template;
    }
}

测试

   //注入我们配置好的RedisTemplate
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Test
    void test() {
        UserPo userPo = UserPo.builder()
                .username("wuhan")
                .password("wuhan520")
                .age(25)
                .build();

        redisTemplate.opsForValue().set("key:user", userPo);
        System.out.println(redisTemplate.opsForValue().get("key:user"));
    }

输出结果:

UserPo(username=wuhan, password=wuhan520, age=25)
上一篇 下一篇

猜你喜欢

热点阅读