前言
Ehcache 是一个成熟的缓存框架,你可以直接使用它来管理你的缓存。
Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现。它支持注解方式使用缓存,非常方便。
本文先通过Ehcache独立应用的范例来介绍它的基本使用方法,然后再介绍与Spring整合的方法。
概述
Ehcache是什么?
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点。它是Hibernate中的默认缓存框架。
Ehcache已经发布了3.1版本。但是本文的讲解基于2.10.2版本。
为什么不使用最新版呢?因为Spring4还不能直接整合Ehcache 3.x。虽然可以通过JCache间接整合,Ehcache也支持JCache,但是个人觉得不是很方便。
安装
Ehcache
如果你的项目使用maven管理,添加以下依赖到你的pom.xml中。
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.2</version> <type>pom</type> </dependency></div>
如果你的项目不使用maven管理,请在 Ehcache官网下载地址 下载jar包。
Spring
如果你的项目使用maven管理,添加以下依赖到你的pom.xml中。
spring-context-support这个jar包中含有Spring对于缓存功能的抽象封装接口。
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.1.4.RELEASE</version> </dependency></div>
Ehcache的使用
HelloWorld范例
接触一种技术最快最直接的途径总是一个Hello World例子,毕竟动手实践印象更深刻,不是吗?
(1) 在classpath下添加ehcache.xml
添加一个名为helloworld的缓存。
<?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"/> <!-- helloworld缓存 --> <cache name="helloworld" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="5" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"/> </ehcache></div>
(2) EhcacheDemo.java
Ehcache会自动加载classpath根目录下名为ehcache.xml文件。
EhcacheDemo的工作步骤如下:
在EhcacheDemo中,我们引用ehcache.xml声明的名为helloworld的缓存来创建Cache对象;
然后我们用一个键值对来实例化Element对象;
将Element对象添加到Cache;
然后用Cache的get方法获取Element对象。
public class EhcacheDemo {
public static void main(String[] args) throws Exception {
// Create a cache manager
final CacheManager cacheManager = new CacheManager();
// create the cache called "helloworld"
final Cache cache = cacheManager.getCache("helloworld");
// create a key to map the data to
final String key = "greeting";
// Create a data element
final Element putGreeting = new Element(key, "Hello, World!");
// Put the element into the data store
cache.put(putGreeting);
// Retrieve the data element
final Element getGreeting = cache.get(key);
// Print the value
System.out.println(getGreeting.getObjectValue());
}
}
</div>
输出
Hello, World!
Ehcache基本操作
Element、Cache、CacheManager是Ehcache最重要的API。
- Element:缓存的元素,它维护着一个键值对。
- Cache:它是Ehcache的核心类,它有多个
Element,并被CacheManager管理。它实现了对缓存的逻辑行为。 - CacheManager:
Cache的容器对象,并管理着Cache的生命周期。
创建CacheManager
下面的代码列举了创建CacheManager的五种方式。
使用静态方法create()会以默认配置来创建单例的CacheManager实例。
newInstance()方法是一个工厂方法,以默认配置创建一个新的CacheManager实例。
此外,newInstance()还有几个重载函数,分别可以通过传入String、URL、InputStream参数来加载配置文件,然后创建CacheManager实例。
// 使用Ehcache默认配置获取单例的CacheManager实例
CacheManager.create();
String[] cacheNames = CacheManager.getInstance().getCacheNames();
// 使用Ehcache默认配置新建一个CacheManager实例
CacheManager.newInstance();
String[] cacheNames = manager.getCacheNames();
// 使用不同的配置文件分别创建一个CacheManager实例
CacheManager manager1 = CacheManager.newInstance("src/config/ehcache1.xml");
CacheManager manager2 = CacheManager.newInstance("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();
// 基于classpath下的配置文件创建CacheManager实例
URL url = getClass().getResource("/anotherconfigurationname.xml");
CacheManager manager = CacheManager.newInstance(url);
// 基于文件流得到配置文件,并创建CacheManager实例
InputStream fis = new FileInputStream(new File
("src/config/ehcache.xml").getAbsolutePath());
try {
CacheManager manager = CacheManager.newInstance(fis);
} finally {
fis.close();
}
</div>
添加缓存
需要强调一点,Cache对象在用addCache方法添加到CacheManager之前,是无效的。
使用CacheManager的addCache方法可以根据缓存名将ehcache.xml中声明的cache添加到容器中;它也可以直接将Cache对象添加到缓存容器中。
Cache有多个构造函数,提供了不同方式去加载缓存的配置参数。
有时候,你可能需要使用API来动态的添加缓存,下面的例子就提供了这样的范例。
// 除了可以使用xml文件中配置的缓存,你也可以使用API动态增删缓存
// 添加缓存
manager.addCache(cacheName);
// 使用默认配置添加缓存
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");
// 使用自定义配置添加缓存,注意缓存未添加进CacheManager之前并不可用
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache test = singletonManager.getCache("testCache");
// 使用特定的配置添加缓存
CacheManager manager = CacheManager.create();
Cache testCache = new Cache(
new CacheConfiguration("testCache", maxEntriesLocalHeap)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
.eternal(false)
.timeToLiveSeconds(60)
.timeToIdleSeconds(30)
.diskExpiryThreadIntervalSeconds(0)
.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)));
manager.addCache(testCache);
</div>

