首页 > 解决方案 > 如何在批量事务期间以编程方式使用 ehcache 从缓存中清除内存?

问题描述

在数据库中插入更多记录(例如 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 中使用它是否正确。

标签: javahibernatespring-bootspring-mvcehcache

解决方案


您可以尝试使用清除所有缓存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()


推荐阅读