Using @Cacheable and @CacheEvict in Spring
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.
Mukesh
Updated on June 05, 2022Comments
-
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 over 6 yearsAs mentioned in the other answer, the value of the key you evict has to be the same than the key you cached.
-
Mukesh over 6 yearsI 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 over 6 yearsOk.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 over 6 yearsYou could use
@CacheEvict( value = "reporties", allEntries = true )
on one method to evict all items from thereporties
cache. -
alirabiee over 6 yearsI'm afraid you have to specify the key in order to identify the specific manager.
-
Mukesh over 6 yearsThat manager key I will pass but what about the method name. i hardcoded the methodname but it doesn't work
-
alirabiee over 6 yearsLet us know how you have written the eviction annotation.