Using @Cacheable and @CacheEvict in Spring

风流意气都作罢 提交于 2020-07-21 07:23:28

问题


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?


回答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 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.




回答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.



来源:https://stackoverflow.com/questions/45856975/using-cacheable-and-cacheevict-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!