Spring Boot2.0 自定义redisCacheManager

Spring Boot2.0 取消了使用RedisTemplate来构建CacheManager。
提供了RedisCacheManager.create(poolFactor) 方法来创建cacheManager。
用了poolFactor嘛,所以pom文件要加一下

1
2
3
4
5
 <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>

好像cacheManager不提供设置默认的缓存过期时间等设置(当然也有可能我没发现- -)。
所以我用了RedisCacheConfiguration来设置默认的缓存过期时间,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
// 缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {

// 初始化一个RedisCacheWriter
RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
// 设置缓存过期时间(秒)
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(1800));
return new RedisCacheManager(cacheWriter,redisCacheConfiguration);
}

当然,自定义key的生成策略跟自定义序列化跟之前差不多,看代码:

  • 修改默认的序列化方式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    // 修改默认的序列化方式
    @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(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(
    RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    StringRedisTemplate template = new StringRedisTemplate();
    setSerializer(template);
    template.setConnectionFactory(redisConnectionFactory);
    return template;
    }
    private void setSerializer(StringRedisTemplate template) {
    @SuppressWarnings({ "rawtypes", "unchecked" })
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    }
  • 自定义key生成策略

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 自定义缓存key生成策略
    @Bean
    public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
    @Override
    public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
    StringBuffer sb = new StringBuffer();
    sb.append(target.getClass().getName());
    sb.append(method.getName());
    for (Object obj : params) {
    sb.append(obj.toString());
    }
    return sb.toString();
    }
    };
    }