skip to Main Content

I am using Redis Cache in my Spring Boot application to store data of multiple rest API’s.

I am clearing Redis cache on a regular interval using Spring Cron Jobs. The method is getting called at required time-slots.

I have verified the logs but the cache is not getting clear and hence it is showing the stale data.

The code where I’m trying to clear the cache.

public class CustomerDerivation {
    @Autowired
    @Qualifier("redisCacheMngr")
    CacheManager redisCacheMngr;

    @Scheduled(cron = "${redis.api.update.interval}")
    @CacheEvict(value = "redis-cache", allEntries = true, cacheNames = {"redis-cache"})
    protected void cacheEvict() {
        redisCacheMngr.getCache("redis-cache").clear();
        logger.info("Evicting ModelCache");
    }
}

Custom cache configuration code.

@Configuration
@Profile("cloud")
public class CacheConfig extends AbstractCloudConfig {
    @Autowired
    Environment env;

    @Bean
    public RedisConnectionFactory brRedisFactory() {
        return connectionFactory().redisConnectionFactory(env.getProperty("model_cache_name"));
    }

    @Bean
    public RedisTemplate<String, Object> brRedisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(brRedisFactory());
        return redisTemplate;
    }

    @Bean(name = "redisCacheMngr")
    public CacheManager cacheManager() {
        RedisCacheManager cacheManager = new RedisCacheManager(brRedisTemplate());
        cacheManager.setUsePrefix(true);
        cacheManager.setTransactionAware(true);
        return cacheManager;
    }
}

How to fix the code to clear the redis cache ?

3

Answers


  1. 1) Have you enabled the cache using @EnableCaching annotation?
    2) why are you using @CacheEvict and clear() in the same method? Both serves the same purpose. Use either one of them.

    Login or Signup to reply.
  2. Check the following:

    1. App is started with the according profile (ie. “cloud”)
    2. @EnabledCaching on your configuration
    3. Avoid to mix @CacheEvict and the CacheManager bean, you have to choose one way for eviction
    4. Extract the @Scheduled method in another “CronJobs” bean to avoid multiple annotations and AOP inside class issues.

    Regards.

    Login or Signup to reply.
  3. Spring use Spring AOP (Aspect Oriented Programming) to implement caching which means you must use public access level on your cacheEvict() method so it can be intercepted by AOP proxy. Otherwise it is like you never annotate your method with @CacheEvict

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search