加入ehcache-1.2.4.jar包
在src目录下加入ehcache.xml文件
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的基本操作
在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");