【问题标题】:Spring caching evictionSpring缓存驱逐
【发布时间】:2020-07-20 00:54:38
【问题描述】:
我无法理解 spring @cacheEvict 注释。它是一种触发缓存驱逐的方法吗?请看下文。
@CacheEvict
public void clearEmployeeById(int id) {
//Do we have to add a method as trigger here in order to trigger the cache eviction? or can we leave this method without implementation
}
``
【问题讨论】:
标签:
spring
spring-boot
caching
spring-cache
【解决方案1】:
需要在@CacheEvict中指定缓存名称
@CacheEvict(value = {"employee"}, allEntries = true)
public void clearEmployeeById(int id) {
//Logic
}
缓存employee 将得到evicted,每当clearEmplyoeeByID() 方法被调用。
将缓存添加到employee
@Cacheable(value = {"employee"})
public Employee addEmployeeById(int id) {
//Logic
return employee;
}
要清除所有缓存,需要使用CacheManager
@Autowired
private CacheManager cacheManager;
@Scheduled(fixedDelay = 86400000)
public boolean evictAllCaches() {
cacheManager.getCacheNames().stream().forEach(c -> cacheManager.getCache(c).clear());
return true;
}