亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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條經驗 獲得超8個贊

許多人建議使用的選項@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 關注
  • 388 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號