1.创建CacheManager,创建ehcache有四种方式:
a.使用默认配置文件创建。在classpath中查找ehcache.xml,如果找不到则使用ehcache.jar中ehcache-failsafe.xml文件
CacheManager manager=CacheManager.create();
b.使用指定配置文件创建。
CacheManager manager=CacheManager.create("src/config/ehcache.xml");
c.从classpath寻找配置文件并创建
Url url=getClass().getResource("/filename.xml");
CacheManager manager=CacheManager.create(url);
d.通过输入流创建
CacheManager manager=null;
InputStream is=new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try{
manager=CacheManager.create(fis);
}catch(IOException e){
e.printStackTrace();
}finally{
fis.close();
}
2.创建Cache
a.取得配置文件中预定义的sampleCache1设置,生成一个cache
Cache cache=manager.getCache("sampleCache1");
b.设置一个默认属性的cache
manager.addCache("test1");
c.新建一个cache,并定义其属性
Cache cache=new Cache("test2",1,true,false,5,2);
manager.addCache(cache);
3.往cache中添加元素
Element ele=new Element("key1","value1");
cache.put(element);
4.从cache中取得元素
Element ele=cache.get("key1");
5.卸载manager,关闭cache
manager.shutdown();
6.在Hibernate中运用ehcache
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhcacheProvider</property>
在hibernate映射文件的每个需要cache的domain中
<hibernate-mapping package="domain">
<class name="User" table="user">
<cache usage="read-write"/>
<id name="id" column="id">
<generator class="native"/>
</id>
...
然后在ehcache.xml中加入类似下面的xml内容
<? xml version="1.0" encoding="utf-8" ?>
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache maxElementsInMemory="300" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false"/>
<cache name="domain.User" maxElementsInMemory="300" eternal="false" timeToIdleSeconds="300"
timeToLiveSeconds="600" overflowToDisk="true"/>
</ehcache>
然后在代码中启动缓存:
c=session.createCriteria(User.class);
c.setCacheable(true);
注:ehcache.xml的配置说明可以查看ehcache.jar中的ehcache.xml和ehcache.xsd