EhCache
- Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
XML配置
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- helloworld缓存 -->
<!-- name : 缓存的名称,可以通过指定名称获取指定的某个Cache对象 -->
<!-- maxElementsInMemory :内存中允许存储的最大的元素个数,0代表无限个 -->
<!-- clearOnFlush:内存数量最大时是否清除。 -->
<!-- eternal :设置缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。根据存储数据的不同,例如一些静态不变的数据如省市区等可以设置为永不过时 -->
<!-- timeToIdleSeconds : 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 -->
<!-- timeToLiveSeconds :缓存数据的 生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。(和上面的两者取最小值) -->
<!-- overflowToDisk:内存不足时,是否启用磁盘缓存。 -->
<!-- maxEntriesLocalDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 -->
<!-- maxElementsOnDisk:硬盘最大缓存个数。 -->
<!-- diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 -->
<!-- diskPersistent:是否在VM重启时存储硬盘的缓存数据。默认值是false。 -->
<!-- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 -->
<!-- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 -->
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
使用
public class MainTest {
@Test
public void test1() {
CacheManager cacheManager = CacheManager.create("./src/main/resources/ehcache.xml");
Cache cache = cacheManager.getCache("HelloWorldCache");
Element element = new Element("key1", "value1");
cache.put(element);
Element value = cache.get("key1");
System.out.println(value);
System.out.println(value.getObjectValue());
cache.remove("key1");
System.out.println(cache.getSize());
cache.flush();
cacheManager.shutdown();
}
}