Spring cache @Cacheable 注解 自身并不是支持缓存过期,
@Configuration
@EnableCaching
public class EruptRedisConfig implements Serializable {
/**
* 功能描述: 自定义 RedisCacheManager
*
* @param: redisConnectionFactory
* @date: 2021/4/12 11:10
*/
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
/**
* 系统默认值五分钟,单位 秒
*/
this.getRedisCacheConfigurationWithTtl(5 * 60),
this.getRedisCacheConfigurationMap()
);
}
/**
* 功能描述: 配置自定义cache过期时间
*
* @date: 2021/4/12 11:12
*/
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
/**
* 缓存token解析的用户信息,默认失效时间五分钟
*/
redisCacheConfigurationMap.put("cache_erupt_user", this.getRedisCacheConfigurationWithTtl(5 * 60));
/**
* TODO
* 其他方法如需缓存以此类推,@Cacheable(value = "cache_user", key = "#token")
* put(cache_user,expireTime)
*/
return redisCacheConfigurationMap;
}
/**
* 功能描述: RedisCache 序列化设置
*
* @param: seconds 单位 秒
* @date: 2021/4/12 11:10
*/
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> 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);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
}
使用实例
@Cacheable(value = "cache_erupt_user", key = "#token")
public EruptUser createOrGetEruptUser(String token) {
}
整理了几百本各类技术电子书,有需要的同学可以,关注公号回复 [ 666 ] 自取。还有想要加技术群的同学可以加我好友,和大佬侃技术、不定期内推,程序员的内点事这都有。