簡體   English   中英

如何在批量事務期間以編程方式使用 ehcache 從緩存中清除內存?

[英]How to clear memory from cache using ehcache programmatically during bulk transaction?

在數據庫中插入更多的記錄(如 50000)需要很多時間。 我發現,由於 hibernate 將對象存儲在其緩存中,而在任何插入或更新時,隨着記錄數量的增加,插入或更新需要更多時間。 我需要知道在插入時緩存將以什么名稱保存,以便我可以使用 @CacheEvict 注釋逐出。 我正在使用 ehcache。

我發現可以使用@CacheEvict。 但我不知道插入的緩存將以什么名稱保存。 我在CacheConfiguration類中創建了緩存,不知道是否正確。 我發現有一種方法可以使用 ehcache.xml 設置緩存名稱,但我們沒有使用它。 我正在使用 ehcache、hibernate 和 spring mvc。

//Setting cache name in CacheConfiguration class:
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
    return cm -> {           
cm.createCache(com.cspl.cashflow.CashflowService.NAME,jcacheConfiguration);
             };
    }

//For loop for inserting:
public static final String NAME = "names";  
 @Cacheable("names")
 public void getNames() {
     logger.info("saving");
    for(int i=1; i<=50000;i++){
        List<Cashflow> cashflowList = new ArrayList<>();
        Cashflow order = new Cashflow(1, "Stark", "Tony", true)         
        cashflowList.add(order);
        cashflowRepository.save(cashflowList);
    if(i%1000==0) {
            evictAllCacheValues();
                }   
        }
     logger.info("saved");
            }

@CacheEvict(value = "names",  allEntries = true)
    public void evictAllCacheValues() {
                      }

//I have also tried using 
@Scheduled(cron = "0 0/30 * * * ?")       // execute after every 30 min 
public void clearCacheSchedule(){
   for(String name:cacheManager.getCacheNames()){
            cacheManager.getCache(name).clear();  // clear cache by name
                           }
                        }

即使在驅逐之后,插入也需要更多時間。 我不知道設置緩存名稱並在@Cacheable 和@CacheEvict 中使用它是否正確。

您可以嘗試使用cache.removeAll()清除所有緩存。

要以編程方式執行,您必須像這樣使用。

Cache cache = getCache(cacheName); // <---- You have to get the instance of //Ehcache with Configuration
  if (null != cache) {
    cache.removeAll();
  }

有關更多詳細信息,請參閱以下鏈接。 https://www.ehcache.org/apidocs/2.9/net/sf/ehcache/Ehcache.html#removeAll()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM