Ehcache 学习

所需jar :ehcache-2.10.2.jar(最新) slf4j-api.jar(依赖)
classpath :ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>  
    <diskStore path="D:/Ehcache" />  

    <!-- maxElementsInMemory 内存中存储的对象的个数, 内存管理的缓存元素数量最大限值 -->
    <!-- overflowToDisk 对象在内存中达到最大个数的时候,是否写入硬盘 -->
    <!-- eternal 表示cache中的对象是否过期,缺省为过期(按照配置中的时间),如果改为true,表示该对象永远不过期。
              即cache中的元素将一直保存在内存中, 不会因为时间超时而丢失,所以在这个值为true的时候,
     timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了 -->
    <!--  如timeToIdleSeconds="3600" 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。即多长时间不访问该缓存,
              那么ehcache就会清除该缓存。默认值为0,值为0意味着元素可以闲置至无限长时间。 --> 
    <!--  如timeToLiveSeconds="100000" 设定元素从创建到过期的时间。对象存活多少秒过期. 
              默认值为0,值为0意味着元素可以存活至无限长时间。 意思是从cache中的某个元素从创建到消亡的时间,
              从创建开始计时,当超过这个时间,这个元素将被从cache中清除。 -->
    <defaultCache   
        maxElementsInMemory="500"   
        eternal="false"   
        timeToIdleSeconds="300"   
        timeToLiveSeconds="1200"   
        overflowToDisk="true" />  

    <cache   
        name="ehcache"   
        maxElementsInMemory="1"   
        eternal="false"   
        timeToLiveSeconds="36000"   
        timeToIdleSeconds="3600"   
        overflowToDisk="true"
        diskExpiryThreadIntervalSeconds="5"
         />   
</ehcache>  

编写ehcache工具类


public class EhcacheUtil {
    private static final String path = "/ehcache.xml";  

    private URL url;  

    private CacheManager manager;  

    private static EhcacheUtil ehCache;  

    private EhcacheUtil(String path) {  
        url = getClass().getResource(path);  
        manager = CacheManager.create(url); 

    }  

    public static EhcacheUtil getInstance() {  
        if (ehCache== null) {  
            ehCache= new EhcacheUtil(path);  
        }  
        return ehCache;  
    }  

    public void put(String cacheName, String key, Object value) {  
        Cache cache = manager.getCache(cacheName);  
        Element element = new Element(key, value);  
        cache.put(element);  
    }  

    public Object get(String cacheName, String key) {  
        Cache cache = manager.getCache(cacheName);  
        Element element = cache.get(key);  
        return element == null ? null : element.getObjectValue();  
    }  

    public Cache get(String cacheName) {  
        return manager.getCache(cacheName);  
    }  

    public void remove(String cacheName, String key) {  
        Cache cache = manager.getCache(cacheName);  
        cache.remove(key);  
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值