我在带有Redis的springboot2.0中使用@cacheable。我已将RedisCacheManager配置如下:
@Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) { RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory); SerializationPair<Object> valueSerializationPair = RedisSerializationContext.SerializationPair .fromSerializer(new GenericJackson2JsonRedisSerializer()); RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); cacheConfiguration = cacheConfiguration.serializeValuesWith(valueSerializationPair); cacheConfiguration = cacheConfiguration.prefixKeysWith("myPrefix"); cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30)); RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter, cacheConfiguration); return redisCacheManager; }
但这使所有密钥的ttl变为30秒,如何为每个具有不同缓存名称的redis缓存配置不同的ttl?
如果使用@cacheable时需要为缓存配置不同的过期时间,则可以使用不同的ttl配置不同的CacheManager,并在服务中使用缓存时指定cacheManager。
@Cacheable(cacheManager = "expireOneHour", value = "onehour", key = "'_onehour_'+#key", sync = true)