在 Spring Boot 中重新加载/刷新缓存

Shu*_*buu 7 java memcached caching ehcache spring-boot

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

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

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

J.*_*nsy 8

显然所有关于你的问题的评论都是正确的。您应该使用 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();
    }

}
Run Code Online (Sandbox Code Playgroud)


Tec*_*ree 2

尝试这样的事情,正如评论中提到的:

    @Caching(evict={@CacheEvict(value="partTypeCache", key="#partKey")})
    public boolean deletePartType(String partKey) { 
      //when this method is invoked the cache is evicted for the requested key
    }
Run Code Online (Sandbox Code Playgroud)

  • 当@Cacheable执行时,它不会在缓存中找到数据,并且会自动刷新/重新填充缓存。 (2认同)