【发布时间】:2021-01-28 21:03:34
【问题描述】:
从同一类的另一个方法调用缓存方法时,Spring 缓存不起作用。
这是一个清楚地解释我的问题的例子。
缓存服务类:
class testServiceImpl{
@CachePut(key = "#result.id", condition = "#result != null")
public List<String> create(String input) {
......
}
@CacheEvict(key="#id")
public void deleteById(Long id) {
.....
}
public void multiDelete(String input) {
if(condition...){
deleteById(2); //Cache is not Evicted here i.e. the records are still present in getAll call but not in Database.
}else{
create(input); //New Data is persisted in DB but the same has not been updated in Cache.
}
@Transactional
@Cacheable
public Map<Long, String> getAll() {
...
}
我也尝试过使用以下解决方案,但未能成功。
//Create a new object of the same class and use the same. In this case, the data is not persisted in DB i.e. it is not deleting the data from DB.
testServiceImpl testService;
...
public void multiDelete(String input) {
if(condition...){
testService.deleteById(2);
}else{
testService.create(input);
}
有人可以帮我解决这个问题吗?
【问题讨论】:
-
@cdalxndr 的答案是正确的。比使用 AspectJ 更好的解决方案是直接调用缓存。您可以通过感染
CacheManager并致电getCache(name)来做到这一点
标签: java spring caching ehcache