Search code examples
springspring-bootcachingspring-cache

Spring caching eviction


I am having trouble with understanding spring @cacheEvict annotation. Does it a method to trigger cache eviction? Please see below.

  @CacheEvict
  public void clearEmployeeById(int id) {
      //Do we have to add a method as trigger here in order to trigger the cache eviction? or can we leave this method without implementation
           
  }
``

Solution

  • You need to specify the cache name in @CacheEvict

    @CacheEvict(value = {"employee"}, allEntries = true)
    public void clearEmployeeById(int id) {
          //Logic
    }
    

    Cache employee will get evicted, Whenever clearEmplyoeeByID() method gets invoked.

    To add cache into employee

    @Cacheable(value = {"employee"})
    public Employee addEmployeeById(int id) {
       //Logic
       return employee;
    }
    

    To clear all cache, you need to use CacheManager

    @Autowired
    private CacheManager cacheManager;
    
    @Scheduled(fixedDelay = 86400000)
    public boolean evictAllCaches() {
        cacheManager.getCacheNames().stream().forEach(c -> cacheManager.getCache(c).clear()); 
        return true;
    }