zhuangjinxin / study

每日学习笔记
0 stars 0 forks source link

spring-boot-starter-data-redis 操作 Redis #1

Open zhuangjinxin opened 4 years ago

zhuangjinxin commented 4 years ago

今日收获:

  1. 知道了 spring boot redis 默认使用的连接池是:lettuce;还可以自己切换到 Jedis;
  2. 第一次看到RedisAutoConfigration类的源码,知道了Redis自动配置做了哪些事情;
  3. 知道了针对key的操作在RedisTemplate中(如:过期时间),针对value的操作需要先找到opsForXxx;
  4. RedisTemplate 的默认序列化是JdkSerializationRedisSerializer;StringRedisTemplate默认的序列化方案是:StringRedisSerializer;也可以自行修改:redisTemplate.setKeySerializer(new StringRedisSerializer());
zhuangjinxin commented 4 years ago

添加依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
</dependencies>

添加配置:

spring.redis.database=0
spring.redis.password=123
spring.redis.port=6379
spring.redis.host=192.168.66.128
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1ms
spring.redis.lettuce.shutdown-timeout=100ms

自动配置:

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
        @Bean
        @ConditionalOnMissingBean(name = "redisTemplate")
        public RedisTemplate<Object, Object> redisTemplate(
                        RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
                RedisTemplate<Object, Object> template = new RedisTemplate<>();
                template.setConnectionFactory(redisConnectionFactory);
                return template;
        }
        @Bean
        @ConditionalOnMissingBean
        public StringRedisTemplate stringRedisTemplate(
                        RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
                StringRedisTemplate template = new StringRedisTemplate();
                template.setConnectionFactory(redisConnectionFactory);
                return template;
        }
}

使用方法:

@Service
public class HelloService {
    @Autowired
    RedisTemplate redisTemplate;
    public void hello() {
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set("k1", "v1");
        Object k1 = ops.get("k1");
        System.out.println(k1);
    }
}
zhuangjinxin commented 4 years ago

参考文章: Spring Boot 操作 Redis,三种方案全解析! Spring Boot 2.X(六):Spring Boot 集成 Redis