1

I was trying to use the removalListener functionality of Caffeine Cache, but it does not work as excepted. Below is the code tried:

public class CaffeineCacheConfig {

    @Autowired EmployeeRepository employeeRepository;

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("customer");
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine<Object, Object> caffeineCacheBuilder() {
        System.out.println("loading data");
        return Caffeine.newBuilder()
                .initialCapacity(100)
                .maximumSize(500)
                .expireAfterWrite(2, TimeUnit.MINUTES)
                .removalListener((key, value, cause) -> {
                    System.out.println("key: "+ key);
                    System.out.println("value: "+value);
                    System.out.println("cause: "+cause);
                    if (cause.wasEvicted()) employeeRepository.save(new Employee("Test Employee"));
                });

    }

}

As per expectation, the key, value and cause should be printed in console and also data should be inserted in DB after 2 minutes has passed for every entry in the cache.

Please help me understand if my understanding is correct or this is some issue.

Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26

0 Answers0