springboot2.0中使用@cacheable时如何为每个redis缓存配置不同的ttl [英] how to configure different ttl for each redis cache when using @cacheable in springboot2.0

查看:68
本文介绍了springboot2.0中使用@cacheable时如何为每个redis缓存配置不同的ttl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 springboot2.0 中使用 @cacheable 和 redis.我已将 RedisCacheManager 配置如下:

I am using @cacheable in springboot2.0 with redis. I have configured RedisCacheManager as follow:

@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;
}

但是这使得所有key的ttl都为30秒,如何为每个具有不同缓存名称的redis缓存配置不同的ttl?

but this make all key's ttl 30 second, how to configure different ttl for each redis cache with different cachename?

推荐答案

如果在使用 @cacheable 时需要为缓存配置不同的过期时间,您可以使用不同的ttl配置不同的CacheManager,并在您的服务中使用缓存时指定cacheManager.

If you need configure different expire time for cache when using @cacheable , you can configure different CacheManager with different ttl,and specify cacheManager when using cache in your service.

 @Cacheable(cacheManager = "expireOneHour", value = "onehour", key = "'_onehour_'+#key", sync = true)

这篇关于springboot2.0中使用@cacheable时如何为每个redis缓存配置不同的ttl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆