java - 如何在批量事务期间以编程方式使用 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 中使用它是否正确。
解决方案
您可以尝试使用清除所有缓存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()
推荐阅读
- extjs - 应用程序崩溃:Java 运行时环境检测到致命错误:[libsystem_platform.dylib+0x15d2] _platform_strlen+0x12
- java - Corretto 11 上的 AWS Elastic Beanstalk Tomcat 8.5 无法连接到 AWS 服务
- visual-studio - 如何为 WinForms 桌面应用程序的 URL 安装托管 MSIX 包
- python - XML 属性值无法匹配我的另一个字典的键,因此我无法替换属性值
- php - 是什么 || 符号在 Preg_replace() PHP 中的意思
- reactjs - React Formik Mui TextField 与自定义输入失去焦点
- servicestack - Servicestack orm lite 不会反序列化嵌套的 json 结构
- go - 在 Go Benchmarks 中将设置/拆卸放在哪里?
- node.js - 将 npm 脚本中的变量设置为文件中的 env var
- regex - 检查选项有效性的正则表达式,不允许重复