Using @Cacheable and @CacheEvict in Spring

16,600

Solution 1

You can think of the cache as a Map<key, value>.

Every time you invoke a method with the @Cacheable annotation you write in that Map a value associated to what you define as they key.

Every time you invoke a method with the @CacheEvict annotation you delete the value associated with the key. You can also delete all the entries in the Map.

Solution 2

The keys passed to Cacheable and CacheEvict annotations must be the same if they are identifying the same data.

If you want to evict your reports cache by the manager's name, you need to both cache and evict solely based on the manager's name.

Share:
16,600
Mukesh
Author by

Mukesh

Updated on June 05, 2022

Comments

  • Mukesh
    Mukesh almost 2 years

    I developed a method that use @Cacheable annotation. The code is:

       @Cacheable(value="reporties" , key="{#root.methodName,#manager.name}")
       public List<Employee> getReportiesForManager(Employee manager){
         // code to fetch reporties its a Spring JDBC call
       }
    

    Now, I want to evict this cache after some events:

    • Some reporties related with manager have been updated (added or removed).

    After that, the cache related with the manager should be evicted, in that way, the application will get new data instead of using the existing one in that cache. I developed the following method for that:

    @CacheEvict(value="reporties",key="{#name}")
    public void evictReportiesCache(String name){}
    

    I call inside the method which updates the relations of the Manager and its reporties. However, this one works intermittently and I am not sure if that's the correct way to evict cache. Also the Cacheable uses #root.methodName as part of key.

    Can someone please help me with this cache eviction?

  • Andres
    Andres over 6 years
    As mentioned in the other answer, the value of the key you evict has to be the same than the key you cached.
  • Mukesh
    Mukesh over 6 years
    I cannot change the key of cacheable as it is not in my control.The key will have both #root.methodName and #manager.name. How to specify the methoname in cache evict to match the key of cacheable
  • Mukesh
    Mukesh over 6 years
    Ok.Will try hardcoding.Thanks, But also this annotation is on lot of methods, do I need to write evict for each those cacheable methods?
  • alirabiee
    alirabiee over 6 years
    You could use @CacheEvict( value = "reporties", allEntries = true ) on one method to evict all items from the reporties cache.
  • alirabiee
    alirabiee over 6 years
    I'm afraid you have to specify the key in order to identify the specific manager.
  • Mukesh
    Mukesh over 6 years
    That manager key I will pass but what about the method name. i hardcoded the methodname but it doesn't work
  • alirabiee
    alirabiee over 6 years
    Let us know how you have written the eviction annotation.