在Spring中使用@Cacheable和@CacheEvict [英] Using @Cacheable and @CacheEvict in Spring

查看:490
本文介绍了在Spring中使用@Cacheable和@CacheEvict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一种使用 @Cacheable 批注的方法。代码是:

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:


  • 与经理相关的某些报告已更新(添加或删除)。

此后,应该清除与管理器相关的缓存,这样,应用程序将获取新数据,而不是使用该缓存中的现有数据。为此,我开发了以下方法:

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){}

我在更新Manager和它的报告。但是,这是间歇性的,因此我不确定这是否是驱逐缓存的正确方法。另外,可缓存对象还使用#root.methodName 作为密钥的一部分。

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?

推荐答案

您可以将缓存视为 Map< key,value>

每次调用带有@Cacheable批注的方法时,都会在Map中写入与定义为键的值相关的值。

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

每次调用带有@CacheEvict批注的方法时,都会删除与键关联的值。您还可以删除地图中的所有条目。

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.

这篇关于在Spring中使用@Cacheable和@CacheEvict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆