简体   繁体   中英

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

It takes lot of time to insert more records like 50000 in the database. I have found that, since hibernate stores objects in its cache while any insert or update it takes more time to insert as the number of records increases. I need to know in what name the cache will be saved while inserting so that I can evict using @CacheEvict annotation. I am using ehcache.

I have found that @CacheEvict can be used. But I don't know in what name the cache for the insert will be saved. I have created a cache in CacheConfiguration class, but I don't know whether it is correct. I have found there is a way to set cache name using ehcache.xml, but we are not using it. I am using ehcache, hibernate and 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
                           }
                        }

Even after evicting, the insert takes more time. i don't know whether setting the cache name and using it in @Cacheable and @CacheEvict are correct.

You can try to clear all the cache using cache.removeAll() .

To do programmatically, you have to use like this.

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

For more details, refer below the link. https://www.ehcache.org/apidocs/2.9/net/sf/ehcache/Ehcache.html#removeAll()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM