echache缓存的简单使用方法

1、需要echache的jar包

2、需要配置文件ehcache.xml和ehcache.xsd,主要是在ehcache.xml中进行配置

3、修改配置文件ehcache.xml  ,例如添加配置如下:

    <cache name="memoryCache"
            maxElementsInMemory="500" <!-- 最大缓存数量 -->
            eternal="true"  <!-- 在内存中永久存在,由于此处设置为true,所以以下两个参数无效 -->
            timeToIdleSeconds="3600"  
            timeToLiveSeconds="7200"
            overflowToDisk="false"/>  
            
     <cache name="reportCache"
            maxElementsInMemory="500"
            eternal="false"  <!-- 不在内存中永久存在 -->
            timeToIdleSeconds="3600"  <!-- 一个小时之内不再用到这个缓存就清理 -->
            timeToLiveSeconds="7200"  <!-- 两个小时以后不管是否用到这个缓存都会被清理 -->
            overflowToDisk="false"/>  <!-- 当超过500是不会写入磁盘 -->

     <cache name="diskCache"   <!-- 以上两种都是内存缓存,这里配置的是磁盘缓存 -->
            maxElementsInMemory="10000"
            overflowToDisk="true"  <!-- 当内存中超过10000, 就写入磁盘 -->
            eternal="false"
            memoryStoreEvictionPolicy="LRU"  <!-- 这里配置的是清除缓存时的策略 -->
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="600"
            timeToIdleSeconds="3600"
            timeToLiveSeconds="100000"
            diskPersistent="false" />  <!-- 不是磁盘永存 -->

这里就建立了三种缓存形式

4、可以建立一个或者多个独立的类,用于对应配置文件中的配置,例如:

package com.cetc32.cache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class ReportCache {
    private static ReportCache reportCache = null;
    private static Cache cache = null;
    
    //实现单例模式
    public static ReportCache getInstance() {
        if(reportCache == null) {
            reportCache = new ReportCache();
        } 
        return reportCache;
    }
    
    //private Cache cache;

    public ReportCache() {
        String path = this.getClass().getResource("/config/ehcache.xml").getFile();

        CacheManager manager = CacheManager.create(path);
        cache = manager.getCache("reportCache");
    }

    /**
     * 设置缓存
     * @param key
     * @param o
     */
    public void setReportCache(String key, Object o) {

        Element element = new Element(key, o);
        cache.put(element);

    }

    /**
     * 从缓存中获得结果
     * @param key
     * @return
     */
    public Object getReportCache(String key) {
        Element aa = cache.get(key);
        Object r = null;
        if (aa != null) {
            r = aa.getObjectValue();
        }
        return r;

    }
    
    /**
     * 清除某个缓存
     * @param key
     */
    public boolean removeReportCache(String key) {
        return cache.remove(key);
    }

    /**
     * 清空全部缓存
     */
    public void removeAllReportCache() {
        cache.removeAll();
    }
    
    /**
     * @return the cache
     */
    public Cache getCache() {
        return cache;
    }



}

这里采用的是单例模式,应用中一个实例即可

6、在程序中使用 ReportCache reportCache = ReportCache.getInstance(); 获取实例就可以进行缓存操作了。

 

posted @ 2015-05-27 19:36  飞天0407  阅读(2765)  评论(0编辑  收藏  举报