是否有可能让Spring的缓存抽象使用给定的项目填充缓存,而不仅仅是让它通读?
想象一下,我有方法Thing getItem(UUID id)
和setItem(UUID id, Thing thing)
。我想在前者上使用@Cacheable
来从缓存中读取它,如果不存在则调用底层方法。调用setter时,我希望将参数thing
添加到缓存中,然后调用该方法,将其持久保存到底层存储。
答案 0 :(得分:1)
我认为它无法做到这一点。它只是让您定义要通过@Cachable
缓存的实例,并通过@CacheEvict
删除它们。据我所知,没有其他方法可以干扰这种工作机制。
您还可以定义自定义注释以实现相同的功能。
答案 1 :(得分:1)
正如Luciano所说,你可以在方法上设置@CachePut注释,但正如他所说,它将导致你修改你的API。这可能是一个优势,取决于您是否喜欢使用流体API样式获得的语义。
你有另一种选择,但它会将你绑定到Spring,并导致你的setItem代码有点麻烦。您始终可以在CacheManager中连接并在setItem方法中设置缓存中的数据。
所以它看起来像这样:
@Autowire private CacheManager cacheManager;
public void setItem(UUID id, Thing thing) {
Cache c = cacheManager.getCache("cacheName");
if (c != null) {
c.put(id, thing);
}
//Do more
}