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 getRedisCacheConfigurationMap() {
    Map redisCacheConfigurationMap = new HashMap<>();
    redisCacheConfigurationMap.put("wxAccessToken", this.getRedisCacheConfigurationWithTtl(3000));

    return redisCacheConfigurationMap;
}

你可能感兴趣的:(springboot redis @Cacheable 设置过期时间)