EHCACHE介绍

加入ehcache-1.2.4.jar包
在src目录下加入ehcache.xml文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<!-- 默认缓存 -->
<defaultCache maxElementsInMemory="10000" eternal="false"
overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />

<!-- 自定义缓存 -->
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="true"
overflowToDisk="true"
/>
<!-- 临时缓存 对象30分钟10秒过期-->
<cache name="TempCache" maxElementsInMemory="10000" eternal="false"
overflowToDisk="true" timeToIdleSeconds="1810" timeToLiveSeconds="1810"/>
</ehcache>


maxElementsInMemory为内存中存放的对象数量,超过设置的数量则把对象存放到<diskStore path="java.io.tmpdir"/>系统的临时磁盘空间中。Eternal为是否永久保留, overflowToDisk为超过设置的数量是否允许保存到磁盘中。

关于timeToLiveSeconds和timeToIdleSeconds

这两个参数很容易误解,看文档根本没用,我仔细分析了ehcache的代码。结论如下:

1、timeToLiveSeconds的定义是:以创建时间为基准开始计算的超时时长;

2、timeToIdleSeconds的定义是:在创建时间和最近访问时间中取出离现在最近的时间作为基准计算的超时时长;

3、如果仅设置了timeToLiveSeconds,则该对象的超时时间=创建时间+timeToLiveSeconds,假设为A;

4、如果没设置timeToLiveSeconds,则该对象的超时时间=min(创建时间,最近访问时间)+timeToIdleSeconds,假设为B;

5、如果两者都设置了,则取出A、B最少的值,即min(A,B),表示只要有一个超时成立即算超时。

EHcache的基本操作
//获取ehcache管理器
CacheManager cacheManager = CacheManager.getInstance();
//获取自定义的缓存
Cache cache = cacheManager.getCache("sampleCache1");
//存放对象到缓存中,更新缓存对象,只需要给一样的key
cache.put(new Element("key1", "value1"));
//取出缓存中的对象
Element element1 = cache.get("key1");
Object value = element1.getObjectValue();

//删除缓存中的对象
cache.remove("key1");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值