如何在大宗交易中以编程方式使用ehcache从缓存中清除内存?

问题描述 投票:-1回答:1

在数据库中插入更多的记录(例如50000)需要花费大量时间。我发现,由于休眠状态将对象存储在其缓存中,而任何插入或更新操作都会随着记录数量的增加而花费更多的时间来插入。我需要知道在插入时将以什么名称保存缓存,以便可以使用@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中使用它是否正确。

java hibernate spring-boot spring-mvc ehcache
1个回答
0
投票

您可以尝试使用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()

© www.soinside.com 2019 - 2024. All rights reserved.