Ehcache 3.X快速使用
简介
Ehcache 是一个开源的高性能缓存,拥有很高的拓展性和伸缩性,广泛使用各种 Java 项目中(如 Hibernate 默认使用 Ehcache作为二级缓存),在目前基于 Java 的缓存方案里,几乎是性能最高的实现,目前新版本的 Ehcache 3.X 通过支持 Terracotta 改善了2.X 版本体验不佳的分布式缓存支持;
Ehcahe 3.X 和 Ehache 2.X 的 API 差异比较大,以下示例以 Ehcache 3.x 为主;
Ehcache 官网:
http://www.ehcache.org
Ehcache 3.X 技术文档:
http://www.ehcache.org/documentation/
使用 Ehcache 需要导入依赖:org.ehcache:ehcache
如在 Gradle 中:
dependencies {
compile 'org.ehcache:ehcache:3.4.0'
}
Hello world
以下通过一个简单的示例,来演示 Ehcache 3.X 的基本使用,Ehcache支持2种配置方式:直接通过编码配置,通过XML配置;
直接编码配置
//构建一个缓存管理器,创建一个默认的缓存 "preConfigured"
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured", //缓存别名
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
ResourcePoolsBuilder.heap(100)) //设置缓存堆容纳元素个数
.build())
.build(true); //创建之后立即初始化
//从缓存管理器中获取预定的缓存
Cache<Long, String> preConfigured
= cacheManager.getCache("preConfigured", Long.class, String.class);
//直接从缓存管理器创建一个新的缓存
Cache<Long, String> myCache = cacheManager.createCache("myCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
ResourcePoolsBuilder.heap