EHCache初步使用指南

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://anthonliu.blogbus.com/logs/510217.html

写的比较初级,后续将加入对配置文件,内存/磁盘存储,优化,虚拟机宕机,日志等的说明
1. EHCache 的特点,系统要求及安装
是一个纯Java ,过程中(也可以理解成插入式)缓存实现
Hibernate2.1,Spring支持EHcache嵌入,自我感觉Hibernate2.1 + EHCache 很过瘾。。(测试结果比Hibernate+JCS 好多了)
支持多CPU服务器
其版本发布前进行了产品级测试
支持:运行环境jdk1.2到5版本(源代码编译需1.4或1.5 版本)
jdk1.4和1.5 版本,需加入apache 的 commons-logging类库 http://jakarta.apache.org/commons/logging.html
jdk1.2和1.3 版本,需加入commons-collections 2.1 版本 http://jakarta.apache.org/commons/collections.html
和 xerces (xml-apis.jar and xercesImpl.jar), 2.5 版本 http://xml.apache.org/xerces2-j/

如果运行环境为IBM JDK1.4版本上的IBM Websphere 5.1,也需加入 commons-collections 类库(如需要)

单独安装Ehcache ,需把ehcache-X.X.jar 和相关类库方到classpath中。
如项目已安装了Hibernate2.1 ,则不需要做什么。。直接可以使用Ehcache

Cache 存储方式 :内存或磁盘

2. 单独使用 EHCache

使用CacheManager 创建并管理Cache
使用默认配置文件创建
CacheManager manager = CacheManager.create();
使用指定配置文件创建
CacheManager manager = CacheManager.create("src/config/ehcache.xml");
从classpathq找寻配置文件并创建
URL url = getClass().getResource("/anothername.xml");
CacheManager manager = CacheManager.create(url);
通过输入流创建
InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try {
manager = CacheManager.create(fis);
} finally {
fis.close();
}

卸载CacheManager ,关闭Cache

manager.shutdown();

使用Caches

取得配置文件中预先 定义的sampleCache1设置,生成一个Cache
Cache cache = manager.getCache("sampleCache1");


设置一个名为test 的新cache,test属性为默认
CacheManager manager = CacheManager.create();
manager.addCache("test");

设置一个名为test 的新cache,并定义其属性
CacheManager manager = CacheManager.create();
Cache cache = new Cache("test", 1, true, false, 5, 2);
manager.addCache(cache);


往cache中加入元素
Element element = new Element("key1", "value1");
cache.put(new Element(element);


从cache中取得元素
Element element = cache.get("key1");



3. 在 Hibernate 中运用EHCache

hibernate.cfg.xml中需设置如下:
2.1版本加入
<property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.Provider</property>
2.1以下版本加入
<property name="hibernate.cache.provider_class">net.sf.hibernate.cache.EhCache</property>

在 Hibernate 映射文件的每个需要Cache的Domain中
<hibernate-mapping>
<class
name="com.somecompany.someproject.domain.Country"
table="ut_Countries"
dynamic-update="false"
dynamic-insert="false"
>
...

</hibernate-mapping>
加入类似如下格式信息:
<cache usage="read-write|nonstrict-read-write|read-only" />
比如:
<cache usage="read-write" />

然后在ehcache.xml中加入
<ehcache>
<cache name="com.somecompany.someproject.domain.Country"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="false"
/>
</ehcache>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值