首页 > 解决方案 > 在 Spring Boot 中重新加载/刷新缓存

问题描述

我正在使用 Spring Boot,而对于缓存,我正在使用 Ehcache。到目前为止它工作正常。但是现在我必须重新加载/刷新,所以我该怎么做才能让我的应用程序不会有任何停机时间。

我在 Spring Ehcache 中尝试了很多方法,但没有奏效,否则必须编写调度程序并重新加载数据。

@Override
@Cacheable(value="partTypeCache", key="#partKey")
public List<PartType> loadPartType(String partKey) throws CustomException {
        return productIdentityDao.loadPartType();
}

标签: javaspring-bootcachingmemcachedehcache

解决方案


显然所有关于您的问题的评论都是正确的。您应该使用 CacheEvict。我在这里找到了解决方案:https ://www.baeldung.com/spring-boot-evict-cache ,它看起来像这样:

您所要做的就是创建一个名为 CacheService 的类并创建方法,该方法将驱逐您拥有的所有缓存对象。然后你注释该方法@Scheduled 并输入你的间隔率。

@Service
public class CacheService {

    @Autowired
    CacheManager cacheManager;

    public void evictAllCaches() {
        cacheManager.getCacheNames().stream()
          .forEach(cacheName -> cacheManager.getCache(cacheName).clear());
    }

    @Scheduled(fixedRate = 6000)
    public void evictAllcachesAtIntervals() {
        evictAllCaches();
    }

}

推荐阅读