Kane
Kane

Reputation: 8172

How to having two caches(redis backend) with different expire time in spring boot

In my spring boot(1.2.6) application, I need different expire policies for different objects. The cache backend is redis.

What's the best practice to archive it?

Upvotes: 1

Views: 2078

Answers (1)

Kane
Kane

Reputation: 8172

I turned it out, currently it works now.

Originally I created different cache with different expire time, however it does not work. Looks like spring redis cache does not use the expire time specified in cache instance.

Not working

@Bean
public Cache cacheObjectName(StringRedisTemplate template) {
    return new RedisCache(CACHE_OBJNAME, CACHE_OBJNAME.getBytes(), template, 10 * 24 * 60 * 60);
}

Finally I had to create different cache manager with different expire time,

Working implementation

@Bean(name = MANAGER_NAME_1D)
public CacheManager cacheManager1D(StringRedisTemplate redisTemplate) throws Exception {
    final RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate(factory), Arrays.asList(CACHE_A, CACHE_B));
    redisCacheManager.setUsePrefix(true);
    redisCacheManager.setDefaultExpiration(60 * 60 * 24);
    return redisCacheManager;
}

Upvotes: 1

Related Questions