写一个用Ehcache读取2G的文件并缓存到临时文件中,最后以List<dto>的形式传出的demo

时间: 2024-05-06 09:15:52 浏览: 14
以下是一个使用 Ehcache 缓存大文件数据的示例代码。假设需要读取的文件为 `large_file.txt`,文件中每行包含两个字段,用空格分隔。 首先,需要在项目中添加 Ehcache 的依赖,并在 Ehcache 配置文件中定义一个缓存区,如下所示: ```xml <ehcache:config xmlns:ehcache="http://www.ehcache.org/v3" xmlns:jcache="http://www.ehcache.org/v3/jsr107"> <ehcache:cache alias="largeFileCache"> <ehcache:resources> <ehcache:heap unit="MB">100</ehcache:heap> </ehcache:resources> </ehcache:cache> </ehcache:config> ``` 这里定义了一个名为 `largeFileCache` 的缓存区,并指定了最大堆内存为 100 MB。 然后,可以编写读取文件并缓存数据的代码: ```java import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.ehcache.spi.loaderwriter.CacheLoaderWriterFactory; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; public class LargeFileCacheDemo { private static final String LARGE_FILE_PATH = "large_file.txt"; private static final String CACHE_ALIAS = "largeFileCache"; public static void main(String[] args) throws Exception { CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache(CACHE_ALIAS, createCacheConfiguration()) .build(true); Cache<String, List<DemoDto>> cache = cacheManager.getCache(CACHE_ALIAS, String.class, getListDtoType()); List<DemoDto> dtos = cache.get(LARGE_FILE_PATH); if (dtos == null) { loadFileAndCache(cache); dtos = cache.get(LARGE_FILE_PATH); } System.out.println(dtos); } private static void loadFileAndCache(Cache<String, List<DemoDto>> cache) throws Exception { Callable<List<DemoDto>> loader = () -> readAndParseFile(); CacheLoaderWriter<String, List<DemoDto>> loaderWriter = cache.getCacheLoaderWriterManager().getLoaderWriter(CACHE_ALIAS); loaderWriter.write(LARGE_FILE_PATH, loader.call()); } private static List<DemoDto> readAndParseFile() throws IOException { List<DemoDto> dtos = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(LARGE_FILE_PATH))) { String line; while ((line = reader.readLine()) != null) { String[] fields = line.split(" "); dtos.add(new DemoDto(fields[0], fields[1])); } } return dtos; } private static CacheConfiguration<String, List<DemoDto>> createCacheConfiguration() { return CacheConfigurationBuilder.newCacheConfigurationBuilder( String.class, getListDtoType(), ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(100, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.GB) .build()) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(30))) .withLoaderWriter(createCacheLoaderWriter()) .build(); } private static CacheLoaderWriterFactory<String, List<DemoDto>> createCacheLoaderWriter() { return new CacheLoaderWriterFactory<String, List<DemoDto>>() { @Override public CacheLoaderWriter<String, List<DemoDto>> createCacheLoaderWriter(String s, ClassLoader classLoader, CacheConfiguration<String, List<DemoDto>> cacheConfiguration) { return new CacheLoaderWriter<String, List<DemoDto>>() { @Override public List<DemoDto> load(String key) throws Exception { return readAndParseFile(); } @Override public void write(String key, List<DemoDto> value) throws Exception { // Do nothing, as the data is already cached by the loader } @Override public void delete(String key) throws Exception { // Do nothing, as the data is not persisted } }; } }; } private static ParameterizedTypeReference<List<DemoDto>> getListDtoType() { return new ParameterizedTypeReference<List<DemoDto>>() {}; } private static class DemoDto { private String field1; private String field2; public DemoDto(String field1, String field2) { this.field1 = field1; this.field2 = field2; } public String getField1() { return field1; } public String getField2() { return field2; } @Override public String toString() { return "DemoDto{" + "field1='" + field1 + '\'' + ", field2='" + field2 + '\'' + '}'; } } } ``` 这个代码中,首先创建了一个 Ehcache 缓存管理器,并在其中定义了名为 `largeFileCache` 的缓存区。使用 `CacheManager.getCache()` 方法获取到 `largeFileCache` 缓存区的实例。然后,通过 `Cache.get()` 方法尝试从缓存区中获取数据。如果缓存中不存在数据,则使用 `CacheLoaderWriter.write()` 方法将数据写入缓存区。 `CacheLoaderWriter` 是一个接口,它定义了缓存装载器和写入器的行为。在这个示例中,使用 `CacheLoaderWriterFactory` 创建了一个 `CacheLoaderWriter` 的实例,它的 `load()` 方法读取文件并返回一个 DTO 对象列表,`write()` 方法不执行任何操作,因为数据已经被装载到缓存中,`delete()` 方法也不执行任何操作,因为数据并没有持久化。 `CacheConfigurationBuilder` 可以用来创建缓存配置对象,这里指定了缓存区的键和值类型,以及缓存区的容量和过期时间。 最后,定义了一个 `DemoDto` 类作为示例的 DTO 对象,它包含两个字符串字段。在 `readAndParseFile()` 方法中,读取文件并将每行解析为一个 `DemoDto` 对象,最终返回一个 `DemoDto` 对象列表。 注意,这个示例中使用了 Java 8 的 Lambda 表达式和函数式接口,需要在编译时指定 `-target 1.8` 或更高版本。

相关推荐

最新推荐

recommend-type

SpringBoot中Shiro缓存使用Redis、Ehcache的方法

主要介绍了SpringBoot中Shiro缓存使用Redis、Ehcache的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

Ehcache分布式缓存与其在SpringBoot应用

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认的 CacheProvider。Ehcache 是一种广泛使用的开源 Java 分布式缓存。主要面向通用缓存,Java EE 和轻量级容器。它具有内存和...
recommend-type

SpringBoot中使用Ehcache的详细教程

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认的 CacheProvider。这篇文章主要介绍了SpringBoot中使用Ehcache的相关知识,需要的朋友可以参考下
recommend-type

debugpy-1.0.0b7-cp36-cp36m-macosx_10_13_x86_64.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

get() { return this.photoState },

这是一个 JavaScript 中的方法定义,它定义了一个名为 `get` 的方法。这个方法没有参数,它返回了 `this.photoState`。在这个方法中,`this` 是指当前对象,而 `photoState` 是该对象的一个属性。通常情况下,`get` 方法用于获取对象的属性值,并且可以在获取属性值之前进行一些逻辑操作。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依