springboot redis @Cacheable 设置过期时间

原文 https://segmentfault.com/q/1010000015203664

思路

使用注解时 指定 key生成策略 

@Cacheable(value = "wxAccessToken", keyGenerator = "keyGenerator")
public AccessToken getAccessToken() {

  }

在 withInitialCacheConfigurations 方法 给名称wxAccessToken指定过期时间

@Bean
@Override
public KeyGenerator keyGenerator() {
    return (o,method,params)->{
        StringBuilder sb = new StringBuilder();
        sb.append(o.getClass().getName());
        sb.append(method.getName());
        for (Object param : params) {
            sb.append(param.toString());
        }
        return sb.toString();
    };
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {

    RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(getRedisCacheConfigurationWithTtl(600))
            .withInitialCacheConfigurations(getRedisCacheConfigurationMap())
            .transactionAware()
            .build();

    log.info("自定义RedisCacheManager加载完成");
    return redisCacheManager;
}

private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer i){
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(i)) // *s 缓存失效
            // 设置key的序列化方式
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
            // 设置value的序列化方式
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
            // 不缓存null值
            .disableCachingNullValues();

}
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
    Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
    redisCacheConfigurationMap.put("wxAccessToken", this.getRedisCacheConfigurationWithTtl(3000));

    return redisCacheConfigurationMap;
}
发布了2 篇原创文章 · 获赞 0 · 访问量 403
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览