Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set expire key at specific time when using Spring caching with Redis

I am spring caching abstraction annotations to apply caching to my service methods.

Since I am using Redis as the cache store, I want to use the option of expiring cache at a specific time, since that is supported by Redis. expireat command in redis can be used to set expire time at a future time.

I am not sure how I can do that for the keys which are part of my cache when using RedisCache.

I tried to customize RedisCacheManager by creating a bean of it.

I see there is a getNativeCache() method exposed. but I did not find any way to set value for expireat using it.

If there is a way to customize RedisCacheManager so that all keys of a specifc cache use the same time as expiry, please let me know.

like image 401
juser Avatar asked Aug 02 '18 18:08

juser


People also ask

How to set the expiry time of a Redis Cache?

Instead of redis template ,Use Redis Cache Manager, pass redistemplate to cacheManager and use its set expires property to which is basically map of String & Long , you can add cache name and set its expiry time i.e time to live (TTL). You can use setDefaultExpiration method of cacheManager to set same expiry time to all the cache.

How does the Spring Boot cache + Redis work?

Last article Spring Boot Cache + redis sets the effective time and automatically refreshes the cache, time support is configured in the configuration file In a time-dependent manner, the Value of the annotation is expanded directly, such as:

What is a persistent Redis key?

Redis keys are persistent by default, meaning that the Redis server will continue to store them unless they are deleted manually. There may, however, be cases where you’ve set a key but you know you will want to delete it after a certain amount of time has passed; in other words, you want the key to be volatile.

How to set TTL value in key level in Redis Cache?

Setting TTL value in key level it is not possible, because org.springframework.data.redis.cache.RedisCacheManager does not provide any methods to configure the TTL value in key despite they have provided it for the cache level. The following steps will help you configure the TTL time in a cache and default level. Adding required maven dependency.


2 Answers

@Bean (name="cacheManager")
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    RedisCacheConfiguration conf_ready_info = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMillis(50000));

    RedisCacheConfiguration conf_base_info = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMillis(60000));

    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<String, RedisCacheConfiguration>();
    cacheConfigurations.put("base_info", conf_base_info);
    cacheConfigurations.put("ready_info", conf_ready_info);

    return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory)
            .withInitialCacheConfigurations(cacheConfigurations).build();
}


@Cacheable(value = "ready_info", key = "#aid")
public String  findByAid(String aid) throws Exception { 
    String readyInfo = "";
    return readyInfo;
}
like image 196
Mr Cho Avatar answered Sep 21 '22 11:09

Mr Cho


Actually there is. Please check below:

RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
            .disableCachingNullValues()
            .entryTtl(<your duration>)
            .computePrefixWith(CacheKeyPrefix.simple())
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory)
            .cacheDefaults(configuration)
            .build();

I am using 2.0.4.RELEASE version of spring boot. And if you are using older versions here is how you can do:

RedisCacheManager cacheManager =
            new RedisCacheManager(
                    redisTemplate,//redis template
                    Arrays.asList("my-cahce"),//loads these caches at startup
                    false);//Do not allow null values
    cacheManager.setLoadRemoteCachesOnStartup(true);
    cacheManager.setCachePrefix(new DefaultRedisCachePrefix());
    cacheManager.setDefaultExpiration(TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));
like image 32
Siva praneeth Alli Avatar answered Sep 18 '22 11:09

Siva praneeth Alli