为了账号安全,请及时绑定邮箱和手机立即绑定

在 spring boot 中重新加载/刷新缓存

在 spring boot 中重新加载/刷新缓存

开满天机 2023-01-05 17:23:59
我正在使用 Spring Boot 并使用 Ehcache 进行缓存。到目前为止一切正常。但是现在我必须重新加载/刷新,所以我该怎么做才能使我的应用程序不会有任何停机时间。我在 Spring Ehcache 中尝试了很多方法,但它没有用,否则必须编写调度程序并重新加载数据。@Override@Cacheable(value="partTypeCache", key="#partKey")public List<PartType> loadPartType(String partKey) throws CustomException {        return productIdentityDao.loadPartType();}
查看完整描述

4 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

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

    }


}


查看完整回答
反对 回复 2023-01-05
?
慕仙森

TA贡献1827条经验 获得超7个赞

许多人建议使用的选项@CacheEvict是正确的。此外,为确保您的缓存(近)始终加载最新数据,即使数据库中的数据更新超出了您正在运行的应用程序的范围,您也需要定期重新加载整个数据集,间隔时间与您应用程序的 SLA 相匹配。在上面建议的解决方案中,添加逻辑以重新加载所有数据,如下所示:


@Service

public class CacheService {


    @Autowired

    CacheManager cacheManager;


    public void refreshAllCaches() {

        cacheManager.getCacheNames().stream()

          .forEach(cacheName -> cacheManager.getCache(cacheName).clear());

        // reload whole dataset here, dummy example here:

        dataRepository.findAll().forEach(a -> cacheManager.getCache("cache-name")).put(a.getKey(), a));

    }


    @Scheduled(fixedRate = 6000)

    public void refreshAllcachesAtIntervals() {

        refreshAllCaches();

    }


}


查看完整回答
反对 回复 2023-01-05
?
智慧大石

TA贡献1946条经验 获得超3个赞

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


    @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

    }


查看完整回答
反对 回复 2023-01-05
?
精慕HU

TA贡献1845条经验 获得超8个赞

除了上述答案外,您还可以在调度程序中使用 cron,这样可以提供更大的灵活性。您可以让调度程序每天、每周、每年、每天中午 12 点等运行,而无需编写大量代码。


@Service 公共类 CacheService {


@Autowired

CacheManager cacheManager;


public void evictAllCaches() {

    cacheManager.getCacheNames().stream()

      .forEach(cacheName -> cacheManager.getCache(cacheName).clear());

}


@Scheduled(cron = "@weekly")

public void evictAllcachesAtIntervals() {

    evictAllCaches();

}

}


查看完整回答
反对 回复 2023-01-05
  • 4 回答
  • 0 关注
  • 284 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信