java缓存框架

java缓存框架

一、启动加载类

import oracle.core.lmx.CoreException;

/**
 * 启动项
 */
public interface StartItem {
    /**
     * 获取启动项名称

     * @return 启动项名称 */
    public String getName();

    /**
     * 加载启动配置信息
     * @throws CoreException
     */
    public void start() throws CoreException;

    /**
     * 销毁启动资源
     */
    public void stop();
}
public class AppMgr {
    private static final String module = AppMgr.class.getName();

    /**
     * 构造器
     */
    private AppMgr() {
        innerStartItems = new ArrayList<StartItem>();
        innerStartItems.add(new Log4j());
        innerStartItems.add(new PlatformConfig());
        innerStartItems.add(new PlatformCacheMgr());
    }

    /**
     * 实例
     */
    private static AppMgr appMgr = new AppMgr();

    /**
     * 获取实例
     * @return 实例
     */
    public static AppMgr getInstance() {
        return appMgr;
    }

    /**
     * 全局变量
     */
    private Bean varBean = new Bean();

    /**
     * 获取全局变量
     * @param key 键值
     * @return 全局变量
     */
    public Object var(String key) {
        return varBean.get(key);
    }

    /**
     * 设置全局变量
     * @param key 键值
     * @param obj varObj
     */
    public void setVar(String key, Object obj) {
        varBean.set(key, obj);
    }
}
import java.io.File;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import com.platform.core.AppMgr;
import com.platform.core.exception.CoreException;
import com.platform.util.XMLUtils;

/**
 * 系统参数配置
 */
public class PlatformConfig implements StartItem {
    public final static String MODULE = PlatformConfig.class.getName();
    /*
     * (non-Javadoc)
     * @see com.cnten.platform.core.start.StartItem#getName()
     */
    public String getName() {
        return "系统参数配置";
    }

    /*
     * (non-Javadoc)
     * @see com.cnten.platform.core.start.StartItem#start()
     */
    public void start() throws CoreException {
        // 加载leopard.xml
        String filePath = AppMgr.getInstance().getHome().concat("WEB-INF/leopard.xml");
        Document docInst = doLoadConfFile(filePath);
        AppMgr.getInstance().setVar(MODULE+"$PLATFORM_CONFIG$", XMLUtils.toBean4Xml(docInst.getRootElement()));
    }

    /*
     * (non-Javadoc)
     * @see com.cnten.platform.core.start.StartItem#stop()
     */
    public void stop() {

    }

    /**
     * 加载配置文件
     * @param filePath filePath
     * @return docInst docInst
     */
    private Document doLoadConfFile(String filePath) {
        File fileInst = new File(filePath);
        SAXReader saxRInst = new SAXReader();
        Document docInst = null;
        try {
            docInst = saxRInst.read(fileInst);
        } catch (DocumentException e) {
            throw new CoreException(e);
        }
        return docInst;
    }
}
import com.platform.core.cache.core.CacheManager;

import oracle.core.lmx.CoreException;

/**
 * 系统缓存组件
 */
public class PlatformCacheMgr implements StartItem {

    /*
     * (non-Javadoc)
     * @see com.platform.core.start.StartItem#getName()
     */
    public String getName() {
        return "系统缓存组件";
    }

    /*
     * (non-Javadoc)
     * @see com.platform.core.start.StartItem#start()
     */
    public void start() throws CoreException {
        CacheManager.getInstance();
    }

    /*
     * (non-Javadoc)
     * @see com.platform.core.start.StartItem#stop()
     */
    public void stop() {
    }

}

二、全局缓存配置

import java.util.ArrayList;
import java.util.List;

import com.platform.core.AppMgr;
import com.platform.core.Metadata.FuncDao;
import com.platform.core.base.Bean;
import com.platform.core.base.IBean;
import com.platform.core.cache.ModelCacheManager;
import com.platform.core.config.vo.Config;
import com.platform.core.start.PlatformConfig;

/**
 * 系统内部全局配置
 */
public class ContextConfig {
    /** modelType TODO */
    private final String modelType = Config.class.getName();
    /** modelCacheManager TODO */
    private final ModelCacheManager modelCacheManager;

    /** singleton instance */
    private static ContextConfig ccInst = null;

    /**
     * Constructor
     */
    private ContextConfig() {
        modelCacheManager = new ModelCacheManager();
        IBean iBean = (IBean) AppMgr.getInstance().var(PlatformConfig.MODULE + "$PLATFORM_CONFIG$");
        for (String key : iBean.getKeys()) {
            IBean tmpBean = new Bean();
            tmpBean.set("CONF_CODE", key);
            tmpBean.set("CONF_VALUE", iBean.get(key));
            modelCacheManager.saveCache(
                key, modelType, new Config(tmpBean));
        }
    }

    /**
     * 取得全局配置
     * @return ccInst 配置实例
     */
    public static ContextConfig getInstance() {
        if (null == ccInst) {
            ccInst = new ContextConfig();
        }
        return ccInst;
    }

    /**
     * 取得配置数据
     * @param key key
     * @param defV 默认值
     * @return rtnObj rtnObj/defV
     */
    public String getConf(String key, String defV) {
        Object rtnVal = getConf(key);
        return rtnVal != null ? String.valueOf(rtnVal) : defV;
    }

    /**
     * 取得配置数据
     * @param key key
     * @return rtnValue rtnValue/null
     */
    public Object getConf(String key) {
        Config config = getConfig(key);
        return config != null ? config.getValue() : null;
    }

    /**
     * 获取参数配置
     * @param key 参数编码
     * @return Config
     */
    public Config getConfig(String key) {
        Config config = (Config) modelCacheManager.getCache(key, modelType);

        if (config == null) {
//            IBean tmpBean = new EntityDAO("SY_CONFIG").byId(key);
        	 IBean tmpBean = new FuncDao("SY_CONFIG").byId(key);
        	 
            if (tmpBean != null) {
                config = new Config(tmpBean);
                if (!config.isFlag()) {
                    config = null;
                } else {
                    modelCacheManager.saveCache(key, modelType, config);
                }
            }
        }
        return config;
    }

    /**
     * 取得list格式存储的数据
     * @param key key
     * @return rtnList rtnList/null
     */
    public List getListConf(String key) {
        final Object tmpObj = getConf(key);
        List rtnList = null == tmpObj ? null : tmpObj instanceof List ? (List) tmpObj : new ArrayList() {
            /** inner serialize */
            private static final long serialVersionUID = 1L;
            {
                add(tmpObj);
            }
        };
        return rtnList;
    }

    /**
     * 清除缓存
     * @param key void
     */
    public void clear(String key) {
        modelCacheManager.removeCache(key, modelType);
    }
}

三、引入缓存实体

public class CacheableWrapper implements java.io.Serializable{

    /** cachedValueKey TODO */
    private String cachedValueKey;
    /** cachedValue TODO */
    private Object cachedValue;

    /**
     * Constructor for CacheableWrapper.
     * @param cachedValueKey String
     * @param cachedValue Object
     */
    public CacheableWrapper(String cachedValueKey, Object cachedValue) {
        this.cachedValueKey = cachedValueKey;
        this.cachedValue = cachedValue;
    }

    /**
     * Method getCachedValueKey.
     * @return String
     */
    public String getCachedValueKey() {
        return cachedValueKey;
    }

    /**
     * Method setCachedValueKey.
     * @param cachedValueKey String
     */
    public void setCachedValueKey(String cachedValueKey) {
        this.cachedValueKey = cachedValueKey;
    }

    /**
     * Method getCachedValue.
     * @return Object
     */
    public Object getCachedValue() {
        return cachedValue;
    }

    /**
     * Method setCachedValue.
     * @param cachedValue Object
     */
    public void setCachedValue(Object cachedValue) {
        this.cachedValue = cachedValue;
    }
}
import java.io.Serializable;
import com.cnten.platform.core.base.IBean;
/**
 * 数据实体抽象类
 */
public abstract class BaseModel implements Serializable {

    /** serialVersionUID TODO */
    private static final long serialVersionUID = -6781923537321799749L;
    /** modified 数据是否修改 */
    private volatile boolean modified;

    public boolean isModified() {
        return modified;
    }

    public void setModified(boolean modified) {
        this.modified = modified;
    }

    public IBean toView() {
        return null;
    }
}
package com.platform.core.config.vo;

import com.platform.core.base.IBean;
import com.platform.core.cache.model.BaseModel;

public class Config extends BaseModel {
    /** serialVersionUID TODO */
    private static final long serialVersionUID = 8582214502055788448L;

    /**
     * 构造函数
     * @param iBean
     */
    public Config(IBean iBean) {
        IBean tBean = iBean;
        code = tBean.get("CONF_CODE", "");
        name = tBean.get("CONF_NAME", "");
        moduleCode = tBean.get("MODULE_CODE", "");
        value = tBean.get("CONF_VALUE");
        comment = tBean.get("CONF_COMMNET", "");
        isFlag = tBean.get("CONF_FLAG", false);
        group = tBean.get("CONF_GROUP", "");

    }

    /** code 变量编码 */
    private String code;
    /** name 变量名称 */
    private String name;
    /** moduleCode 所属模块编码 */
    private String moduleCode;
    /** value 变量值 */
    private Object value;
    /** comment 变量说明,详细说明 */
    private String comment;
    /** isFlag 变量启用标志:1 启用 2 禁用 */
    private boolean isFlag;
    /** group 配置组 */
    private String group;

    /**
     * Method getCode.
     * @return String
     */
    public String getCode() {
        return code;
    }

    /**
     * Method getName.
     * @return String
     */
    public String getName() {
        return name;
    }

    /**
     * Method getModuleCode.
     * @return String
     */
    public String getModuleCode() {
        return moduleCode;
    }

    /**
     * Method getValue.
     * @return String
     */
    public Object getValue() {
        return value;
    }

    /**
     * Method getComment.
     * @return String
     */
    public String getComment() {
        return comment;
    }

    /**
     * Method isFlag.
     * @return boolean
     */
    public boolean isFlag() {
        return isFlag;
    }

    /**
     * Method getGroup.
     * @return String
     */
    public String getGroup() {
        return group;
    }
}

三、缓存管理器

import java.util.Iterator;

import com.platform.core.AppMgr;
import com.platform.core.base.IBean;
import com.platform.core.cache.core.api.ICache;
import com.platform.core.cache.core.api.StringKey;
import com.platform.core.cache.core.impl.CacheKey;
import com.platform.core.cache.lru.CacheableWrapper;
import com.platform.core.cache.lru.LRUCache;
import com.platform.core.components.encache.EhcacheConf;
import com.platform.core.components.encache.EncacheProvider;
import com.platform.core.exception.CoreException;
import com.platform.core.start.PlatformConfig;
import com.platform.core.util.Constant;
import com.platform.core.util.Debug;

/**
 * 缓存管理类
 */
public class CacheManager {
    /** module 缓存类包路径 */
    public static final String module = CacheManager.class.getName();
    /** cacheManager 缓存工厂 类 */
    private static CacheManager cacheFactory = null;
    /** cache TODO */
    private ICache cache;

    /**
     * 构造函数
     */
    private CacheManager() {
        IBean iBean = (IBean) AppMgr.getInstance().var(PlatformConfig.MODULE + "$PLATFORM_CONFIG$");
        String cacheType = iBean.get("cache-type", Constant.STR_YES);
        if (Constant.STR_YES.equals(cacheType)) {
            cache = new LRUCache("cache.xml");
        } else if (Constant.STR_NO.equals(cacheType)) {
            EhcacheConf ehcacheConf = new EhcacheConf("leopard_ehcache.xml", "leopardCache");
            cache = new EncacheProvider(ehcacheConf);
        } else {
            throw new CoreException("缓存配置有误,请检查配置!");
        }
    }

    /**
     * 实例化工厂类
     * @return CacheManager
     */
    public static CacheManager getInstance() {
        if (cacheFactory == null) {
            cacheFactory = new CacheManager();
        }
        return cacheFactory;
    }

    /**
     * 清除缓存
     */
    public void clear() {
        if (cache != null) {
            cache.clear();
        }
    }

    /**
     * 根据StringKey获取对应缓存实体
     * @param skey StringKey
     * @return Object
     */
    public Object fetchObject(StringKey skey) {
        return fetchObject(skey.getKey());
    }

    /**
     * 根据主键编码获取对应数据缓存实体
     * @param skey String
     * @return Object
     */
    public Object fetchObject(String skey) {
        CacheableWrapper cw = (CacheableWrapper) cache.get(skey);
        if (cw != null) {
            return cw.getCachedValue();
        } else {
            return null;
        }
    }

    /**
     * 缓存数据实体
     * @param ckey CacheKey
     * @param value Object
     */
    public void putObject(CacheKey ckey, Object value) {
        if (ckey == null) {
            return;
        } else {
            cache.put(ckey.getKey(), new CacheableWrapper(ckey.getDataKey(), value));
            // Debug.logVerbose((new StringBuilder()).append(
            // "[Leopard]<-cache->save cache: ").append(
            // ckey.getKey()).append(", cache size:").append(cache.size()).toString(),
            // module);
            return;
        }
    }

    /**
     * 缓存数据实体
     * @param skey String
     * @param value Object
     */
    public void putObject(String skey, Object value) {
        if (skey == null) {
            return;
        } else {
            cache.put(skey, new CacheableWrapper(skey, value));
            // Debug.logVerbose((new
            // StringBuilder()).append("[Leopard]<-cache->save cache: ").append(
            // skey).append(", cache size:").append(cache.size()).toString(),
            // module);

            return;
        }
    }

    /**
     * 清除缓存实体
     * @param skey StringKey
     */
    public void removeObject(StringKey skey) {
        if (skey == null) {
            return;
        } else {
            cache.remove(skey.getKey());
            Debug.logVerbose((new StringBuilder()).append("[Leopard]<-cache->remove the object of ")
                .append(skey).append(" from cache").toString(), module);
            return;
        }
    }

    /**
     * 清除缓存实体
     * @param skey String
     */
    public void removeObject(String skey) {
        if (skey == null) {
            return;
        } else {
            cache.remove(skey);
            Debug.logVerbose((new
                StringBuilder()).append("[Leopard]<-cache->remove the object of ")
                .append(skey).append(" from cache").toString(), module);
            return;
        }
    }

    /**
     * 清除缓存实体
     * @param dataKey Object
     */
    public void removeCache(Object dataKey) {
        if (dataKey == null) {
            return;
        }
        try {
            Iterator ckIter = cache.keySet().iterator();
            do {
                if (!ckIter.hasNext()) {
                    break;
                }
                Object o = ckIter.next();
                String key = (String) o;
                Object cachedValue = cache.get(key);
                if (cachedValue instanceof CacheableWrapper) {
                    CacheableWrapper cw = (CacheableWrapper) cachedValue;
                    if (cw.getCachedValueKey().equals(dataKey.toString())) {
                        removeObject(key);
                    }
                }
            } while (true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取缓存对象
     * @return CacheI
     */
    public ICache getCache() {
        return cache;
    }

}
import com.platform.core.cache.core.CacheManager;
import com.platform.core.cache.core.api.CacheKeyFactory;
import com.platform.core.cache.core.impl.CacheKey;
import com.platform.core.cache.model.ModelCacheKeyFactory;

/**
 * 实体缓存管理工厂类
 */
public class ModelCacheManager {
    /** cacheManager 缓存管理器 */
    protected CacheManager cacheManager;

    /** cacheKeyFactory 缓存主键工厂 类 */
    private final CacheKeyFactory cacheKeyFactory;

    /**
     * 构造函数
     * @param cacheManager 缓存管理器
     */
    public ModelCacheManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
        this.cacheKeyFactory = new ModelCacheKeyFactory();
    }
    private static ModelCacheManager manager = null;
    /**
     * 构造函数
     */
    public ModelCacheManager() {
        this.cacheManager = CacheManager.getInstance();
        this.cacheKeyFactory = new ModelCacheKeyFactory();
    }
    public static ModelCacheManager getInstance(){
        if(manager==null){
            manager = new ModelCacheManager();
        }

        return manager;
    }

    /**
     * 保存实体缓存数据
     * @param dataKey 数据主键
     * @param modelClass 实体类包路径
     * @param model void 存储实体
     */
    public void saveCache(String dataKey, String modelClass, Object model) {
        CacheKey ckey = cacheKeyFactory.createCacheKey(dataKey, modelClass);
        cacheManager.putObject(ckey, model);
    }

    /**
     * 获取缓存数据
     * @param dataKey String
     * @param modelClass String
     * @return Object
     */
    public Object getCache(String dataKey, String modelClass) {
        CacheKey ckey = cacheKeyFactory.createCacheKey(dataKey, modelClass);
        return cacheManager.fetchObject(ckey);
    }

    /**
     * 删除缓存数据
     * @param dataKey String
     * @param modelClass String
     */
    public void removeCache(String dataKey, String modelClass) {
        CacheKey ckey = cacheKeyFactory.createCacheKey(dataKey, modelClass);
        cacheManager.removeObject(ckey);
    }

    /**
     * 删除所有主键编码为dataKey的缓存数据
     * @param dataKey String
     */
    public void removeCache(String dataKey) {
        cacheManager.removeObject(dataKey);
    }

    public void clearCache() {
        cacheManager.clear();
    }
}

四、缓存工厂类

import java.util.Collection;

/**
 * 缓存类接口
 */
public interface ICache {
    /**
     * 获取缓存值
     * @param obj key
     * @return Object
     */
    public abstract Object get(Object obj);

    /**
     * 设置缓存值
     * @param obj Object
     * @param obj1 Object
     */
    public abstract void put(Object obj, Object obj1);

    /**
     * 删除缓存值
     * @param obj Object
     */
    public abstract void remove(Object obj);

    /**
     * 缓存长度值
     * @return long
     */
    public abstract long size();

    /**
     * 清除缓存
     */
    public abstract void clear();

    /**
     * 是否包含该缓存
     * @param obj Object
     * @return boolean
     */
    public abstract boolean contain(Object obj);

    /**
     * 所有缓存主键值
     * @return Collection
     */
    public abstract Collection keySet();
}
/**
 * 主键生成类接口
 */
public interface StringKey {

    /**
     * 获取主键编码
     * @return String
     */
    public abstract String getKey();
}
import com.platform.core.cache.core.impl.CacheKey;
/**
 * 缓存主键生成类
 */
public abstract class StringCacheKeyFactory {

    /**
     * 构造函数
     */
    public StringCacheKeyFactory() {
    }

    /**
     * 根据数据主键、数据类型生成缓存主键
     * @param dataKey String 数据主键
     * @param dataType String 数据类型
     * @return CacheKey
     */
    public CacheKey createCacheKey(String dataKey, String dataType) {
        return createCacheKeyImp(dataKey, dataType);
    }

    /**
     * Method createCacheKeyImp.
     * @param dataKey String
     * @param dataType String
     * @return CacheKey
     */
    public abstract CacheKey createCacheKeyImp(String dataKey, String dataType);

}
import com.platform.core.cache.core.impl.CacheKey;

/**
 * 缓存主键生成工厂类
 */
public abstract class CacheKeyFactory {

    /**
     * 构造函数
     */
    public CacheKeyFactory() {
    }

    /**
     * 创建缓存主键
     * @param dataKey String
     * @param typeName String
     * @return CacheKey
     */
    public CacheKey createCacheKey(String dataKey, String typeName) {
        return createCacheKeyImp(dataKey, typeName);
    }

    /**
     * 创建缓存主键
     * @param s String
     * @param s1 String
     * @return CacheKey
     */
    public abstract CacheKey createCacheKeyImp(String s, String s1);

}

五、缓存组件

/**
 * Ehcache组件参数配置类
 */
public class EhcacheConf {

    /** ehcacheConfFileName 缓存配置文件 */
    private String ehcacheConfFileName;
    /** predefinedCacheName 缓存名称 */
    private String predefinedCacheName;

    /**
     * 构造函数
     * @param ehcacheConfFileName String 自定义缓存配置文件
     * @param predefinedCacheName String 自定义缓存名称
     */
    public EhcacheConf(String ehcacheConfFileName, String predefinedCacheName) {
        this.ehcacheConfFileName = "leopard_ehcache.xml";
        this.predefinedCacheName = "leopardCache";
        this.ehcacheConfFileName = ehcacheConfFileName;
        this.predefinedCacheName = predefinedCacheName;
    }

    /**
     * 获取自定义配置文件
     * @return String
     */
    public String getEhcacheConfFileName() {
        return ehcacheConfFileName;
    }

    /**
     * 设置自定义配置文件
     * @param ehcacheConfFileName String 自定义配置文件名称
     */
    public void setEhcacheConfFileName(String ehcacheConfFileName) {
        this.ehcacheConfFileName = ehcacheConfFileName;
    }

    /**
     * 获取自定义缓存名称
     * @return String
     */
    public String getPredefinedCacheName() {
        return predefinedCacheName;
    }

    /**
     * 设置缺省缓存名称
     * @param predefinedCacheName String
     */
    public void setPredefinedCacheName(String predefinedCacheName) {
        this.predefinedCacheName = predefinedCacheName;
    }
}

六、工厂管理类

import java.util.Collection;
import com.platform.core.cache.core.api.ICache;
import com.platform.core.util.PropsUtil;

/**
 * 采用最近最久未使用策略处理缓存.
 */
public class LRUCache
    implements ICache {
    /** cache 缓存实体 */
    private final CacheUtil cache;

    /**
     * 构造函数
     * @param configFileName 缓存配置文件
     */
    public LRUCache(String configFileName) {
        PropsUtil propsUtil = new PropsUtil(configFileName);
        cache = new CacheUtil(propsUtil);
    }

    /**
     * 获取缓存对象
     * @param key 键
     * @return Object 值
     * @see com.platform.core.cache.core.api.ICache#get(Object)
     */
    public Object get(Object key) {
        return cache.get(key);
    }

    /**
     * 设置缓存对象
     * @param key 键
     * @param value 值
     * @see com.platform.core.cache.core.api.ICache#put(Object, Object)
     */
    public void put(Object key, Object value) {
        cache.put(key, value);
    }

    /**
     * 删除缓存对象
     * @param key 键
     * @see com.platform.core.cache.core.api.ICache#remove(Object)
     */
    public void remove(Object key) {
        cache.remove(key);
    }

    /**
     * 获取缓存容器中的对象个数
     * @return long
     * @see com.platform.core.cache.core.api.ICache#size()
     */
    public long size() {
        return cache.size();
    }

    /**
     * 清除所有缓存
     * @see com.platform.core.cache.core.api.ICache#clear()
     */
    public void clear() {
        cache.clearAllCaches();
    }

    /**
     * 判断主键是否在缓存中
     * @param key Object
     * @return boolean
     * @see com.platform.core.cache.core.api.ICache#contain(Object)
     */
    public boolean contain(Object key) {
        return cache.containsKey(key);
    }

    /**
     * 获取主键集合
     * @return Collection
     * @see com.platform.core.cache.core.api.ICache#keySet()
     */
    public Collection keySet() {
        return cache.keySet();
    }
}
import java.util.Collection;
import com.platform.core.cache.core.api.ICache;
import com.platform.core.util.FileLocator;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import oracle.core.lmx.CoreException;

public class EncacheProvider implements ICache {

    /** module 类包路径 */
    private static final String module = EncacheProvider.class.getName();

    /** manager ehcache缓存管理器 */
    private net.sf.ehcache.CacheManager manager;
    private final EhcacheConf ehcacheConf;

    /**
     * Constructor for EncacheProvider.
     * @param ehcacheConf EhcacheConf
     */
    public EncacheProvider(EhcacheConf ehcacheConf) {
        this.ehcacheConf = ehcacheConf;
        FileLocator fileLocator = new FileLocator();
        java.io.InputStream pathCongfgName = fileLocator.getConfStream(ehcacheConf
            .getEhcacheConfFileName());
        manager = new CacheManager(pathCongfgName);
    }

    /**
     * Method start.
     * @throws CoreException
     * @see com.platform.core.start.StartItem#start()
     */
    public void start() throws CoreException {
        synchronized (CacheManager.class) {
            if (manager == null) {
                FileLocator fileLocator = new FileLocator();
                java.io.InputStream pathCongfgName = fileLocator.getConfStream(ehcacheConf
                    .getEhcacheConfFileName());
                manager = new CacheManager(pathCongfgName);
            }
        }
    }

    /**
     * Method getName.
     * @return String * @see com.platform.core.start.StartItem#getName()
     */
    public String getName() {
        return "EhCache缓存组件";
    }

    /**
     * Method stop.
     * @see com.platform.core.start.StartItem#stop()
     */
    public void stop() {
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        cache.removeAll();
        manager.removeCache(ehcacheConf.getPredefinedCacheName());
        manager.removalAll();
        manager.clearAll();
        manager.shutdown();
        manager = null;
    }

    /**
     * Method get.
     * @param key Object
     * @return Object
     * @see com.platform.core.cache.core.api.ICache#get(Object)
     */
    public Object get(Object key) {
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        Element e = cache.get(key);
        if (e == null) {
            return null;
        } else {
            return e.getObjectValue();
        }
    }

    /**
     * Method put.
     * @param key Object
     * @param value Object
     * @see com.platform.core.cache.core.api.ICache#put(Object, Object)
     */
    public void put(Object key, Object value) {

        Element element = new Element(key, value);
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        cache.put(element);
    }

    /**
     * Method remove.
     * @param key Object
     * @see com.platform.core.cache.core.api.ICache#remove(Object)
     */
    public void remove(Object key) {
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        cache.remove(key);
    }

    /**
     * Method size.
     * @return long
     * @see com.platform.core.cache.core.api.ICache#size()
     */
    public long size() {
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        return cache.getMemoryStoreSize();
    }

    /**
     * Method clear.
     * @see com.platform.core.cache.core.api.ICache#clear()
     */
    public void clear() {
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        cache.removeAll();
    }

    /**
     * Method contain.
     * @param key Object
     * @return boolean
     * @see com.platform.core.cache.core.api.ICache#contain(Object)
     */
    public boolean contain(Object key) {
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        return cache.isKeyInCache(key);
    }

    /**
     * Method keySet.
     * @return Collection
     * @see com.platform.core.cache.core.api.ICache#keySet()
     */
    public Collection keySet() {
        net.sf.ehcache.Cache cache = manager.getCache(ehcacheConf.getPredefinedCacheName());
        return cache.getKeys();
    }

}
import java.io.Serializable;

import com.platform.core.cache.core.api.StringKey;

public class CacheKey
    implements StringKey, Serializable {

    /** cacheType TODO */
    private String cacheType;
    /** dataKey TODO */
    private String dataKey;
    /** dataTypeName TODO */
    private String dataTypeName;

    /**
     * 构造函数
     * @param cacheType 缓存类型
     * @param dataKey 存储主键
     * @param dataTypeName 存储实体
     */
    public CacheKey(String cacheType, String dataKey, String dataTypeName) {
        this.cacheType = cacheType;
        this.dataTypeName = dataTypeName;
        this.dataKey = dataKey;
    }

    /**
     * TODO$
     * @return String
     */
    public String getCacheType() {
        return cacheType;
    }

    /**
     * TODO$
     * @return String
     */
    public String getDataKey() {
        return dataKey;
    }

    public String getDataTypeName() {
        return dataTypeName;
    }

    public void setCacheType(String cacheType) {
        this.cacheType = cacheType;
    }

    public void setDataKey(String dataKey) {
        this.dataKey = dataKey;
    }

    public void setDataTypeName(String dataTypeName) {
        this.dataTypeName = dataTypeName;
    }

    public String getKey() {
        StringBuffer buffer = new StringBuffer(cacheType);
        buffer.append(dataTypeName);
        if (dataKey != null)
            buffer.append(dataKey.toString());
        return buffer.toString();
    }

    public String toString() {
        return getKey();
    }
}
import com.platform.core.cache.core.api.CacheKeyFactory;
import com.platform.core.cache.core.impl.CacheKey;

/**
 * 缓存主键工厂类
 */
public class ModelCacheKeyFactory extends CacheKeyFactory {
    /** CACHE_TYPE_MODEL TODO */
    public final static String CACHE_TYPE_MODEL = "Model";

    /**
     * Method createCacheKeyImp.
     * @param dataKey String
     * @param modelClassName String
     * @return CacheKey
     */
    public CacheKey createCacheKeyImp(String dataKey, String modelClassName) {
        return new CacheKey(CACHE_TYPE_MODEL, dataKey, modelClassName);
    }
}

七、缓存操作工具类

import com.platform.core.util.dom4j.XMLProperties;

/**
 * 读取配置文件工具类
 */
public class PropsUtil {
    /** module 类包路径 */
    public static final String module = PropsUtil.class.getName();
    /** ENCODING TODO */
    public static String ENCODING = "UTF-8";
    /** properties TODO */
    private XMLProperties properties;
    /** fileLocator TODO */
    private FileLocator fileLocator;

    /**
     * Constructor for PropsUtil.
     * @param configureFile String
     */
    public PropsUtil(String configureFile) {
        fileLocator = new FileLocator();
        loadProperties(configureFile);
    }

    /**
     * Method loadProperties.
     * @param configName String
     */
    public void loadProperties(String configName) {
        java.io.InputStream pathCongfgName = fileLocator.getConfStream(configName);
        if (pathCongfgName == null) {
            System.out.println((new StringBuilder()).append(" cann't load config file:-->").append(
                configName).toString());
            return;
        } else {
            properties = new XMLProperties(pathCongfgName);
            return;
        }
    }

    /**
     * Method getProperty.
     * @param name String
     * @return String
     */
    public String getProperty(String name) {
        String res = properties.getProperty(name);
        if (res == null)
            res = "";
        return res;
    }

    /**
     * Method getChildrenProperties.
     * @param name String
     * @return String[]
     */
    public String[] getChildrenProperties(String name) {
        return properties.getChildrenProperties(name);
    }

    /**
     * Method getChildrenValues.
     * @param name String
     * @return String[]
     */
    public String[] getChildrenValues(String name) {
        return properties.getChildrenPropertiesValues(name);
    }

    /**
     * Method setProperty.
     * @param name String
     * @param value String
     */
    public void setProperty(String name, String value) {
        properties.setProperty(name, value);
    }

}
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.platform.core.base.Bean;
import com.platform.core.base.IBean;
import com.platform.util.CommonUtils;

public class XMLProperties {
	private Document doc;
	public Document getDoc() {
		return doc;
	}


	private Map propertyCache;

	public XMLProperties(String fileName) {
		propertyCache = new HashMap();
		try {
			SAXReader builder = new SAXReader();
			DataUnformatFilter format = new DataUnformatFilter();
			builder.setXMLFilter(format);
			doc = builder.read(new File(fileName));
		} catch (Exception e) {
			System.err
					.println("Error creating XML parser in PropertyManager.java");
			e.printStackTrace();
		}
	}

	public XMLProperties(InputStream inputStream) {
		propertyCache = new HashMap();
		try {
			SAXReader builder = new SAXReader();
			DataUnformatFilter format = new DataUnformatFilter();
			builder.setXMLFilter(format);
			doc = builder.read(inputStream);
		} catch (Exception e) {
			System.err
					.println("Error creating XML parser in PropertyManager.java");
			e.printStackTrace();
		}
	}

	public String getProperty(String name) {
		String proVal = (String) propertyCache.get(name);

		if (proVal == null) {
			Element element = getElementByPath(name);
			if (!CommonUtils.isNullOrEmpty(element.getText())) {
				proVal = element.getText().trim();
				propertyCache.put(name, proVal);
			}
		}
		return proVal;
	}

	public String[] getChildrenProperties(String parent) {
		Element element = getElementByPath(parent);
		if (element == null) {
			return new String[0];
		}

		List children = element.elements();
		int childCount = children.size();
		String childrenNames[] = new String[childCount];
		for (int i = 0; i < childCount; i++)
			childrenNames[i] = ((Element) children.get(i)).getName();

		return childrenNames;
	}

	public String[] getChildrenPropertiesValues(String parent) {
		Element element = getElementByPath(parent);
		if (element == null) {
			return new String[0];
		}

		List children = element.elements();
		int childCount = children.size();
		String childrenNames[] = new String[childCount];
		for (int i = 0; i < childCount; i++)
			childrenNames[i] = ((Element) children.get(i)).getText();
		return childrenNames;
	}

	public void setProperty(String name, String value) {
		propertyCache.put(name, value);
		String propName[] = parsePropertyName(name);
		Element element = doc.getRootElement();
		for (int i = 0; i < propName.length; i++) {
			if (element.element(propName[i]) == null)
				element.addElement(propName[i]);
			element = element.element(propName[i]);
		}

		element.setText(value);
	}

	public void deleteProperty(String name) {
		String propName[] = parsePropertyName(name);
		Element element = doc.getRootElement();
		for (int i = 0; i < propName.length - 1; i++) {
			element = element.element(propName[i]);
			if (element == null)
				return;
		}

		if (element.getName() == propName[propName.length - 1]) {
			element.getParent().remove(element);
		}
	}

	private String[] parsePropertyName(String name) {
		int size = 1;
		for (int i = 0; i < name.length(); i++)
			if (name.charAt(i) == '.')
				size++;

		String propName[] = new String[size];
		StringTokenizer tokenizer = new StringTokenizer(name, ".");
		for (int i = 0; tokenizer.hasMoreTokens(); i++)
			propName[i] = tokenizer.nextToken();

		return propName;
	}

	/**
	 * TODO$
	 *
	 * @param parent
	 * @return Element
	 */
	public Element getElementByPath(String parent) {
		String propName[] = parsePropertyName(parent);
		Element element = doc.getRootElement();
		for (int i = 0; i < propName.length; i++) {
			element = element.element(propName[i]);
			if (element == null) {
				return null;
			}
		}
		return element;
	}

	public IBean toBean() {
		IBean map = new Bean();
		Element root = doc.getRootElement();
		for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
			Element e = (Element) iterator.next();
			// System.out.println(e.getName());
			List list = e.elements();
			if (list.size() > 0) {
				map.set(e.getName(), toBean(e));
			} else
				map.set(e.getName(), e.getText());
		}
		return map;
	}

	private IBean toBean(Element e) {
		IBean map = new Bean();
		List list = e.elements();
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Element iter = (Element) list.get(i);
				List mapList = new ArrayList();

				if (iter.elements().size() > 0) {
					IBean m = toBean(iter);
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!(obj instanceof ArrayList)) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(m);
						}
						if (obj instanceof ArrayList) {
							mapList = (List) obj;
							mapList.add(m);
						}
						map.set(iter.getName(), mapList);
					} else
						map.set(iter.getName(), m);
				} else {
					if (map.get(iter.getName()) != null) {
						Object obj = map.get(iter.getName());
						if (!(obj instanceof ArrayList)) {
							mapList = new ArrayList();
							mapList.add(obj);
							mapList.add(iter.getText());
						}
						if (obj instanceof ArrayList) {
							mapList = (List) obj;
							mapList.add(iter.getText());
						}
						map.set(iter.getName(), mapList);
					} else
						map.set(iter.getName(), iter.getText());
				}
			}
		} else
			map.set(e.getName(), e.getText());
		return map;
	}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;

public class FileLocator {

    public FileLocator() {
    }

    /**
     * Method getConfPathXmlFile.
     * @param filePathName String
     * @return String
     */
    public String getConfPathXmlFile(String filePathName) {
        int i = filePathName.lastIndexOf(".xml");
        String name = filePathName.substring(0, i);
        name = name.replace('.', '/');
        name = (new StringBuilder()).append(name).append(".xml").toString();
        return getConfFile(name);
    }

    /**
     * Method getConfPathXmlStream.
     * @param filePathName String
     * @return InputStream
     */
    public InputStream getConfPathXmlStream(String filePathName) {
        int i = filePathName.lastIndexOf(".xml");
        String name = filePathName.substring(0, i);
        name = name.replace('.', '/');
        name = (new StringBuilder()).append(name).append(".xml").toString();
        return getConfStream(name);
    }

    /**
     * Method getConfFile.
     * @param fileName String
     * @return String
     */
    public String getConfFile(String fileName) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null)
            classLoader = getClass().getClassLoader();
        URL confURL = classLoader.getResource(fileName);
        if (confURL == null)
            confURL = classLoader.getResource((new StringBuilder()).append("META-INF/").append(fileName)
                .toString());
        if (confURL == null)
            return null;
        File file1 = new File(confURL.getFile());
        if (file1.isFile()) {
            System.out.println((new StringBuilder()).append(" locate file: ").append(confURL.getFile())
                .toString());
            return confURL.getFile();
        } else {
            System.err.println((new StringBuilder()).append(" it is not a file: ")
                .append(confURL.getFile()).toString());
            return null;
        }
    }

    /**
     * Method getConfStream.
     * @param fileName String
     * @return InputStream
     */
    public InputStream getConfStream(String fileName) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
        	classLoader = getClass().getClassLoader();
        }
        InputStream stream = classLoader.getResourceAsStream(fileName);
        if (stream == null) {
        	stream = classLoader.getResourceAsStream((new StringBuilder()).append("META-INF/").append(fileName).toString());
        }
		try {
			if(stream == null) {
				stream = new FileInputStream(new File(fileName));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
        return stream;
    }
}
package com.platform.core.cache.lru;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.platform.core.util.ConcurrentLinkedList;
import com.platform.core.util.PropsUtil;
import com.platform.util.CommonUtils;

public class CacheUtil {
    /** module 类路径 */
    public static String module = CacheUtil.class.getName();
    /** keyLRUList LRU主键集合 */
    public final ConcurrentLinkedList keyLRUList;
    /** cacheLineTable 缓存载体 */
    public final Map cacheLineTable;
    /** hitCount 命中率 */
    protected volatile long hitCount;
    /** missCount 丢失率 */
    protected volatile long missCount;
    /** maxSize 最大缓存数 */
    protected volatile long maxSize;
    /** expireTime 有效时间 */
    protected volatile long expireTime;
    /** useSoftReference 软件引用 */
    protected volatile boolean useSoftReference;

    /**
     * 根据配置文件进行参数初始化
     * @param propsUtil PropsUtil
     */
    public CacheUtil(PropsUtil propsUtil) {
        keyLRUList = new ConcurrentLinkedList();
        cacheLineTable = new ConcurrentHashMap();
        hitCount = 0L;
        missCount = 0L;
        maxSize = 0L;
        expireTime = 0L;
        useSoftReference = false;
        setPropertiesParams(propsUtil, "default");
    }

    /**
     * 初始化系统缓存参数
     * @param maxSize int 最大缓存数
     * @param expireTime long 有效期,例:new Date().getTime().
     * @param useSoftReference boolean 是否软引用
     */
    public CacheUtil(int maxSize, long expireTime, boolean useSoftReference) {
        keyLRUList = new ConcurrentLinkedList();
        cacheLineTable = new ConcurrentHashMap();
        hitCount = 0L;
        missCount = 0L;
        this.maxSize = 0L;
        this.expireTime = 0L;
        this.useSoftReference = false;
        this.maxSize = maxSize;
        this.expireTime = expireTime;
        this.useSoftReference = useSoftReference;
    }

    /**
     * Method setPropertiesParams.
     * @param propsUtil PropsUtil
     * @param cacheName String
     */
    protected void setPropertiesParams(PropsUtil propsUtil, String cacheName) {
        if (propsUtil == null) {
            System.err.println(" UtilCache propsUtil not yet set!! ");
            return;
        }
        try {
            String value = propsUtil.getProperty((new StringBuilder()).append("cache.").append(cacheName)
                .append(".maxSize").toString());
            if (!CommonUtils.isNullOrEmpty(value)) {
                Long longValue = new Long(value);
                if (longValue != null) {
                    maxSize = longValue.longValue();
                }
            }
        } catch (Exception e) {
        }
        try {
            String value = propsUtil.getProperty((new StringBuilder()).append("cache.").append(cacheName)
                .append(".expireTime").toString());
            if (!CommonUtils.isNullOrEmpty(value)) {
                Long longValue = new Long(value);
                if (longValue != null) {
                    expireTime = longValue.longValue();
                }
            }
        } catch (Exception e) {
        }
        try {
            String value = propsUtil.getProperty((new StringBuilder()).append("cache.").append(cacheName)
                .append(".useSoftReference").toString());
            if (!CommonUtils.isNullOrEmpty(value)) {
                useSoftReference = "true".equals(value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Method put.
     * @param key Object
     * @param value Object
     */
    public void put(Object key, Object value) {
        if (key == null || value == null) {
            return;
        }
        try {
            if (maxSize > 0L) {
                if (cacheLineTable.containsKey(key)) {
                    keyLRUList.moveFirst(key);
                } else {
                    keyLRUList.addFirst(key);
                }
            }
            if (expireTime > 0L) {
                cacheLineTable.put(key, new CacheLine(value, useSoftReference, System.currentTimeMillis()));
            } else {
                cacheLineTable.put(key, new CacheLine(value, useSoftReference));
            }
            if (maxSize > 0L && (long) cacheLineTable.size() > maxSize) {
                Object lastKey = keyLRUList.getLast();
                removeObject(lastKey);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * Method get.
     * @param key Object
     * @return Object
     */
    public Object get(Object key) {
        if (key == null) {
            return null;
        }
        if (!cacheLineTable.containsKey(key)) {
            return null;
        }
        CacheLine line = (CacheLine) cacheLineTable.get(key);
        if (hasExpired(line)) {
            removeObject(key);
            line = null;
        }
        if (line == null) {
            missCount++;
            return null;
        }
        hitCount++;
        if (maxSize > 0L) {
            keyLRUList.moveFirst(key);
        }
        return line.getValue();
    }

    /**
     * Method remove.
     * @param key Object
     */
    public void remove(Object key) {
        removeObject(key);
    }

    /**
     * Method removeObject.
     * @param key Object
     */
    private void removeObject(Object key) {
        if (key == null) {
            missCount++;
        }
        CacheLine line = (CacheLine) cacheLineTable.remove(key);
        if (line != null) {
            if (maxSize > 0L) {
                keyLRUList.remove(key);
            }
        } else {
            missCount++;
        }
    }

    /**
     * Method keySet.
     * @return Set
     */
    public Set keySet() {
        return cacheLineTable.keySet();
    }

    /**
     * Method values.
     * @return Collection
     */
    public Collection values() {
        return cacheLineTable.values();
    }

    /**
     * 清除缓存
     */
    public void clear() {
        cacheLineTable.clear();
        keyLRUList.clear();
        clearCounters();
    }

    /**
     * 清除所有缓存
     */
    public void clearAllCaches() {
        clear();
    }

    /**
     * Method getHitCount.
     * @return long
     */
    public long getHitCount() {
        return hitCount;
    }

    /**
     * Method getMissCount.
     * @return long
     */
    public long getMissCount() {
        return missCount;
    }

    public void clearCounters() {
        hitCount = 0L;
        missCount = 0L;
    }

    /**
     * Method setMaxSize.
     * @param maxSize long
     */
    public void setMaxSize(long maxSize) {
        if (maxSize <= 0L)
            keyLRUList.clear();
        else if (maxSize > 0L && this.maxSize <= 0L) {
            for (Iterator keys = cacheLineTable.keySet().iterator(); keys.hasNext(); keyLRUList.add(keys
                .next()));
        }
        if (maxSize > 0L && (long) cacheLineTable.size() > maxSize) {
            Object lastKey;
            for (; (long) cacheLineTable.size() > maxSize; removeObject(lastKey))
                lastKey = keyLRUList.getLast();

        }
        this.maxSize = maxSize;
    }

    /**
     * Method getMaxSize.
     * @return long
     */
    public long getMaxSize() {
        return maxSize;
    }

    /**
     * Method setExpireTime.
     * @param expireTime long
     */
    public void setExpireTime(long expireTime) {
        if (this.expireTime <= 0L && expireTime > 0L) {
            long currentTime = System.currentTimeMillis();
            CacheLine line;
            for (Iterator values = cacheLineTable.values().iterator(); values.hasNext(); line
                .setLoadTime(currentTime))
                line = (CacheLine) values.next();

        } else if (this.expireTime <= 0L)
            if (expireTime <= 0L)
                ;
        this.expireTime = expireTime;
    }

    /**
     * Method getExpireTime.
     * @return long
     */
    public long getExpireTime() {
        return expireTime;
    }

    /**
     * Method getUseSoftReference.
     * @return boolean
     */
    public boolean getUseSoftReference() {
        return useSoftReference;
    }

    /**
     * Method size.
     * @return long
     */
    public long size() {
        return (long) cacheLineTable.size();
    }

    /**
     * Method containsKey.
     * @param key Object
     * @return boolean
     */
    public boolean containsKey(Object key) {
        CacheLine line = (CacheLine) cacheLineTable.get(key);
        if (hasExpired(line)) {
            removeObject(key);
            line = null;
        }
        return line != null;
    }

    /**
     * Method hasExpired.
     * @param key Object
     * @return boolean
     */
    public boolean hasExpired(Object key) {
        if (key == null) {
            return false;
        } else {
            CacheLine line = (CacheLine) cacheLineTable.get(key);
            return hasExpired(line);
        }
    }

    /**
     * Method hasExpired.
     * @param line CacheLine
     * @return boolean
     */
    protected boolean hasExpired(CacheLine line) {
        if (line == null)
            return false;
        if (useSoftReference && line.getValue() == null) {
            return true;
        }
        if (expireTime <= 0L)
            return false;
        if (line.getLoadTime() <= 0L)
            return true;
        return line.getLoadTime() + expireTime < System.currentTimeMillis();
    }

    public void clearExpired() {
        Iterator keys = cacheLineTable.keySet().iterator();
        do {
            if (!keys.hasNext())
                break;
            Object key = keys.next();
            if (hasExpired(key))
                removeObject(key);
        } while (true);
    }

}
import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ConcurrentLinkedList {
    /** readWriteLock TODO */
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
    /** readLock TODO */
    private final Lock readLock;
    /** writeLock TODO */
    private final Lock writeLock;
    /** keyLRUList TODO */
    public final LinkedList keyLRUList = new LinkedList();

    /**
     * 构造函数
     */
    public ConcurrentLinkedList() {
        readLock = readWriteLock.readLock();
        writeLock = readWriteLock.writeLock();
    }

    /**
     * Method add.
     * @param o Object
     */
    public void add(Object o) {
        writeLock.lock();
        try {
            keyLRUList.add(o);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            writeLock.unlock();
        }

    }

    /**
     * Method addFirst.
     * @param key Object
     */
    public void addFirst(Object key) {
        writeLock.lock();
        try {
            keyLRUList.addFirst(key);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    /**
     * Method moveFirst.
     * @param key Object
     */
    public void moveFirst(Object key) {

        writeLock.lock();
        try {
            keyLRUList.remove(key);
            keyLRUList.addFirst(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }

    }

    /**
     * Method getLast.
     * @return Object
     */
    public Object getLast() {
        readLock.lock();
        Object obj = null;
        try {
            obj = keyLRUList.getLast();
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            readLock.unlock();
        }
        return obj;
    }

    /**
     * Method size.
     * @return int
     */
    public int size() {
        readLock.lock();
        int i = 0;
        try {
            i = keyLRUList.size();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
        return i;
    }

    /**
     * Method remove.
     * @param key Object
     */
    public void remove(Object key) {
        readLock.lock();
        try {
            keyLRUList.remove(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    public void clear() {
        writeLock.lock();
        try {
            keyLRUList.clear();
        } catch (Exception e) {
            writeLock.unlock();
        } finally {
            writeLock.unlock();
        }
    }
}
import java.lang.ref.SoftReference;

public class CacheLine {

    /** valueRef TODO */
    private Object valueRef;
    /** loadTime TODO */
    private long loadTime;
    /** useSoftReference TODO */
    private boolean useSoftReference;

    /**
     * Constructor for CacheLine.
     * @param value Object
     * @param useSoftReference boolean
     */
    public CacheLine(Object value, boolean useSoftReference) {
        valueRef = null;
        loadTime = 0L;
        this.useSoftReference = false;
        this.useSoftReference = useSoftReference;
        if (this.useSoftReference) {
            valueRef = new SoftReference(value);
        } else {
            valueRef = value;
        }
    }

    /**
     * Constructor for CacheLine.
     * @param value Object
     * @param useSoftReference boolean
     * @param loadTime long
     */
    public CacheLine(Object value, boolean useSoftReference, long loadTime) {
        this(value, useSoftReference);
        this.loadTime = loadTime;
    }

    /**
     * Method getValue.
     * @return Object
     */
    public Object getValue() {
        if (valueRef == null)
            return null;
        if (useSoftReference)
            return ((SoftReference) valueRef).get();
        else
            return valueRef;
    }

    /**
     * Method getLoadTime.
     * @return long
     */
    public long getLoadTime() {
        return loadTime;
    }

    /**
     * Method setLoadTime.
     * @param loadTime long
     */
    public void setLoadTime(long loadTime) {
        this.loadTime = loadTime;
    }

    /**
     * Method isUseSoftReference.
     * @return boolean
     */
    public boolean isUseSoftReference() {
        return useSoftReference;
    }

    /**
     * Method setUseSoftReference.
     * @param useSoftReference boolean
     */
    public void setUseSoftReference(boolean useSoftReference) {
        this.useSoftReference = useSoftReference;
    }
}

读取xml文档

<?xml version="1.0" encoding="UTF-8" ?>
<leopard>
	<!-- 产品线编码 -->
	<config-item>
        <item-name>productLineCode</item-name>
        <item-value>LEOPARD</item-value>
    </config-item>
    <!--缓存类型-->
    <cache-type>1</cache-type>
    <!--数据源-->
  <!--  <datasource>
    	<application description="应用数据源">
    		<item id="appDS" default="true">jdbc/oracle</item>
    	</application>
    	<version description="版本数据源">
    		<item id="appVersionDS" >jdbc/version</item>
    	</version>
    </datasource>-->

	<datasource id="appDS" name="Oracle 服务数据源" default="true" >jdbc/oracle</datasource>
<!-- 	<datasource id="appServerDS" name="MySql 服务数据源" default="true" >jdbc/mySql</datasource> -->
	<!-- 
	<datasource id="appVersionDS" name="版本服务数据源">jdbc/version</datasource>
    -->
</leopard>

cache.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
  <cache>
    <default>
      <maxSize>10000</maxSize>
      <expireTime>3600000</expireTime><!-- 1小时后过期 -->
      <useSoftReference>false</useSoftReference>
    </default>
  </cache>
</config>

leopard_ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: leopard_ehcache.xml 7680 2011-07-14 07:37:12Z zhangliang $ -->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd" >

    <!--
    CacheManager Configuration
    ==========================
    An ehcache.xml corresponds to a single CacheManager.
    
    See instructions below or the ehcache schema (ehcache.xsd) on how to configure.

    System property tokens can be specified in this file which are replaced when the configuration
    is loaded. For example multicastGroupPort=${multicastGroupPort} can be replaced with the
    System property either from an environment variable or a system property specified with a
    command line switch such as -DmulticastGroupPort=4446.

    DiskStore configuration
    =======================

    The diskStore element is optional. To turn off disk store path creation, comment out the diskStore
    element below.

    Configure it if you have overflowToDisk or diskPersistent enabled for any cache.

    If it is not configured, and a cache is created which requires a disk store, a warning will be
     issued and java.io.tmpdir will automatically be used.

    diskStore has only one attribute - "path". It is the path to the directory where
    .data and .index files will be created.

    If the path is one of the following Java System Property it is replaced by its value in the
    running VM. For backward compatibility these are not specified without being enclosed in the ${token}
    replacement syntax.

    The following properties are translated:
    * user.home - User's home directory
    * user.dir - User's current working directory
    * java.io.tmpdir - Default temp file path
    * ehcache.disk.store.dir - A system property you would normally specify on the command line
      e.g. java -Dehcache.disk.store.dir=/u01/myapp/diskdir ...

    Subdirectories can be specified below the property e.g. java.io.tmpdir/one

    -->
    <diskStore path="java.io.tmpdir"/>

    <!--
    CacheManagerEventListener
    =========================
    Specifies a CacheManagerEventListenerFactory which is notified when Caches are added
    or removed from the CacheManager.

    The attributes of CacheManagerEventListenerFactory are:
    * class - a fully qualified factory class name
    * properties - comma separated properties having meaning only to the factory.

    Sets the fully qualified class name to be registered as the CacheManager event listener.

    The events include:
    * adding a Cache
    * removing a Cache

    Callbacks to listener methods are synchronous and unsynchronized. It is the responsibility
    of the implementer to safely handle the potential performance and thread safety issues
    depending on what their listener is doing.

    If no class is specified, no listener is created. There is no default.
    -->
    <cacheManagerEventListenerFactory class="" properties=""/>
 
    <!--
    CacheManagerPeerProvider
    ========================
    (For distributed operation)

    Specifies a CacheManagerPeerProviderFactory which will be used to create a
    CacheManagerPeerProvider, which discovers other CacheManagers in the cluster.

    One or more providers can be configured. The first one in the ehcache.xml is the default, which is used
    for replication and bootstrapping.

    The attributes of cacheManagerPeerProviderFactory are:
    * class - a fully qualified factory class name
    * properties - comma separated properties having meaning only to the factory.

    Providers are available for RMI, JGroups and JMS as shown following.

    RMICacheManagerPeerProvider
    +++++++++++++++++++++++++++

    Ehcache comes with a built-in RMI-based distribution system with two means of discovery of
    CacheManager peers participating in the cluster:
    * automatic, using a multicast group. This one automatically discovers peers and detects
      changes such as peers entering and leaving the group
    * manual, using manual rmiURL configuration. A hardcoded list of peers is provided at
      configuration time.

    Configuring Automatic Discovery:
    Automatic discovery is configured as per the following example:
    <cacheManagerPeerProviderFactory
                        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
                        properties="hostName=fully_qualified_hostname_or_ip,
                                    peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
                                    multicastGroupPort=4446, timeToLive=32"/>

    Valid properties are:
    * peerDiscovery (mandatory) - specify "automatic"
    * multicastGroupAddress (mandatory) - specify a valid multicast group address
    * multicastGroupPort (mandatory) - specify a dedicated port for the multicast heartbeat
      traffic
    * timeToLive - specify a value between 0 and 255 which determines how far the packets will
      propagate.

      By convention, the restrictions are:
      0   - the same host
      1   - the same subnet
      32  - the same site
      64  - the same region
      128 - the same continent
      255 - unrestricted

     * hostName - the hostname or IP of the interface to be used for sending and receiving multicast packets
       (relevant to mulithomed hosts only)

    Configuring Manual Discovery:
    Manual discovery requires a unique configuration per host. It is contains a list of rmiURLs for the peers, other
    than itself. So, if we have server1, server2 and server3 the configuration will be:

    In server1's configuration:
    <cacheManagerPeerProviderFactory class=
                          "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
                          properties="peerDiscovery=manual,
                          rmiUrls=//server2:40000/sampleCache1|//server3:40000/sampleCache1
                          | //server2:40000/sampleCache2|//server3:40000/sampleCache2"
                          propertySeparator="," />

    In server2's configuration:
    <cacheManagerPeerProviderFactory class=
                          "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
                          properties="peerDiscovery=manual,
                          rmiUrls=//server1:40000/sampleCache1|//server3:40000/sampleCache1
                          | //server1:40000/sampleCache2|//server3:40000/sampleCache2"
                          propertySeparator="," />

    In server3's configuration:
    <cacheManagerPeerProviderFactory class=
                          "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
                          properties="peerDiscovery=manual,
                          rmiUrls=//server1:40000/sampleCache1|//server2:40000/sampleCache1
                          | //server1:40000/sampleCache2|//server2:40000/sampleCache2"
                          propertySeparator="," />


    Valid properties are:
    * peerDiscovery (mandatory) - specify "manual"
    * rmiUrls (mandatory) - specify a pipe separated list of rmiUrls, in the form
                            //hostname:port
    * hostname (optional) - the hostname is the hostname of the remote CacheManager peer. The port is the listening
      port of the RMICacheManagerPeerListener of the remote CacheManager peer.
    
    JGroupsCacheManagerPeerProvider
    +++++++++++++++++++++++++++++++
    <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
                                     properties="connect=UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;
                                     mcast_send_buf_size=150000;mcast_recv_buf_size=80000):
                                     PING(timeout=2000;num_initial_members=6):
                                     MERGE2(min_interval=5000;max_interval=10000):
                                     FD_SOCK:VERIFY_SUSPECT(timeout=1500):
                                     pbcast.NAKACK(gc_lag=10;retransmit_timeout=3000):
                                     UNICAST(timeout=5000):
                                     pbcast.STABLE(desired_avg_gossip=20000):
                                     FRAG:
                                     pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=false)"
                                     propertySeparator="::"
            />
     The only property necessary is the connect String used by jgroups to configure itself. Refer to the Jgroups documentation for explanation
     of all the protocols. The example above uses UDP multicast. If the connect property is not specified the default JGroups connection will be
     used.       


    JMSCacheManagerPeerProviderFactory
    ++++++++++++++++++++++++++++++++++
    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.jms.JMSCacheManagerPeerProviderFactory"
            properties="..."
            propertySeparator=","
            />

    The JMS PeerProviderFactory uses JNDI to maintain message queue independence. Refer to the manual for full configuration
    examples using ActiveMQ and Open Message Queue.

    Valid properties are:
    * initialContextFactoryName (mandatory) - the name of the factory used to create the message queue initial context.
    * providerURL (mandatory) - the JNDI configuration information for the service provider to use.
    * topicConnectionFactoryBindingName (mandatory) - the JNDI binding name for the TopicConnectionFactory
    * topicBindingName (mandatory) - the JNDI binding name for the topic name
    * getQueueBindingName (mandatory only if using jmsCacheLoader) - the JNDI binding name for the queue name
    * securityPrincipalName - the JNDI java.naming.security.principal
    * securityCredentials - the JNDI java.naming.security.credentials
    * urlPkgPrefixes - the JNDI java.naming.factory.url.pkgs
    * userName - the user name to use when creating the TopicConnection to the Message Queue
    * password - the password to use when creating the TopicConnection to the Message Queue
    * acknowledgementMode - the JMS Acknowledgement mode for both publisher and subscriber. The available choices are
                            AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE and SESSION_TRANSACTED. The default is AUTO_ACKNOWLEDGE.
    -->
    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=100"
            propertySeparator=","
            />


    <!--
    CacheManagerPeerListener
    ========================
    (Enable for distributed operation)

    Specifies a CacheManagerPeerListenerFactory which will be used to create a
    CacheManagerPeerListener, which listens for messages from cache replicators participating in the cluster.

    The attributes of cacheManagerPeerListenerFactory are:
    class - a fully qualified factory class name
    properties - comma separated properties having meaning only to the factory.

    Ehcache comes with a built-in RMI-based distribution system. The listener component is
    RMICacheManagerPeerListener which is configured using
    RMICacheManagerPeerListenerFactory. It is configured as per the following example:

    <cacheManagerPeerListenerFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
        properties="hostName=fully_qualified_hostname_or_ip,
                    port=40001,
                    remoteObjectPort=40002,
                    socketTimeoutMillis=120000"
                    propertySeparator="," />

    All properties are optional. They are:
    * hostName - the hostName of the host the listener is running on. Specify
      where the host is multihomed and you want to control the interface over which cluster
      messages are received. Defaults to the host name of the default interface if not
      specified.
    * port - the port the RMI Registry listener listens on. This defaults to a free port if not specified.
    * remoteObjectPort - the port number on which the remote objects bound in the registry receive calls.
                         This defaults to a free port if not specified.
    * socketTimeoutMillis - the number of ms client sockets will stay open when sending
      messages to the listener. This should be long enough for the slowest message.
      If not specified it defaults to 120000ms.

    -->
    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>
    
 
    <!--
    Cache configuration
    ===================

    The following attributes are required.

    name:
    Sets the name of the cache. This is used to identify the cache. It must be unique.

    maxElementsInMemory:
    Sets the maximum number of objects that will be created in memory

	maxElementsOnDisk:
    Sets the maximum number of objects that will be maintained in the DiskStore
	The default value is zero, meaning unlimited.

    eternal:
    Sets whether elements are eternal. If eternal,  timeouts are ignored and the
    element is never expired.

    overflowToDisk:
    Sets whether elements can overflow to disk when the memory store
    has reached the maxInMemory limit.

    The following attributes and elements are optional.

    timeToIdleSeconds:
    Sets the time to idle for an element before it expires.
    i.e. The maximum amount of time between accesses before an element expires
    Is only used if the element is not eternal.
    Optional attribute. A value of 0 means that an Element can idle for infinity.
    The default value is 0.

    timeToLiveSeconds:
    Sets the time to live for an element before it expires.
    i.e. The maximum time between creation time and when an element expires.
    Is only used if the element is not eternal.
    Optional attribute. A value of 0 means that and Element can live for infinity.
    The default value is 0.

    diskPersistent:
    Whether the disk store persists between restarts of the Virtual Machine.
    The default value is false.

    diskExpiryThreadIntervalSeconds:
    The number of seconds between runs of the disk expiry thread. The default value
    is 120 seconds.

    diskSpoolBufferSizeMB:
    This is the size to allocate the DiskStore for a spool buffer. Writes are made
    to this area and then asynchronously written to disk. The default size is 30MB.
    Each spool buffer is used only by its cache. If you get OutOfMemory errors consider
    lowering this value. To improve DiskStore performance consider increasing it. Trace level
    logging in the DiskStore will show if put back ups are occurring.

    clearOnFlush:
    whether the MemoryStore should be cleared when flush() is called on the cache.
    By default, this is true i.e. the MemoryStore is cleared.

    memoryStoreEvictionPolicy:
    Policy would be enforced upon reaching the maxElementsInMemory limit. Default
    policy is Least Recently Used (specified as LRU). Other policies available -
    First In First Out (specified as FIFO) and Less Frequently Used
    (specified as LFU)

    Cache elements can also contain sub elements which take the same format of a factory class
    and properties. Defined sub-elements are:

    * cacheEventListenerFactory - Enables registration of listeners for cache events, such as
      put, remove, update, and expire.

    * bootstrapCacheLoaderFactory - Specifies a BootstrapCacheLoader, which is called by a
      cache on initialisation to prepopulate itself.

    * cacheExtensionFactory - Specifies a CacheExtension, a generic mechansim to tie a class
      which holds a reference to a cache to the cache lifecycle.

    * cacheExceptionHandlerFactory - Specifies a CacheExceptionHandler, which is called when
      cache exceptions occur.

    * cacheLoaderFactory - Specifies a CacheLoader, which can be used both asynchronously and
      synchronously to load objects into a cache. More than one cacheLoaderFactory element
      can be added, in which case the loaders form a chain which are executed in order. If a
      loader returns null, the next in chain is called.

    RMI Cache Replication
    +++++++++++++++++++++

    Each cache that will be distributed needs to set a cache event listener which replicates
    messages to the other CacheManager peers. For the built-in RMI implementation this is done
    by adding a cacheEventListenerFactory element of type RMICacheReplicatorFactory to each
    distributed cache's configuration as per the following example:

    <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
         properties="replicateAsynchronously=true,
         replicatePuts=true,
         replicatePutsViaCopy=false,
         replicateUpdates=true,
         replicateUpdatesViaCopy=true,
         replicateRemovals=true
         asynchronousReplicationIntervalMillis=<number of milliseconds"
         propertySeparator="," />

    The RMICacheReplicatorFactory recognises the following properties:

    * replicatePuts=true|false - whether new elements placed in a cache are
      replicated to others. Defaults to true.

    * replicatePutsViaCopy=true|false - whether the new elements are
      copied to other caches (true), or whether a remove message is sent. Defaults to true.  

    * replicateUpdates=true|false - whether new elements which override an
      element already existing with the same key are replicated. Defaults to true.

    * replicateRemovals=true - whether element removals are replicated. Defaults to true.

    * replicateAsynchronously=true | false - whether replications are
      asynchronous (true) or synchronous (false). Defaults to true.

    * replicateUpdatesViaCopy=true | false - whether the new elements are
      copied to other caches (true), or whether a remove message is sent. Defaults to true.

    * asynchronousReplicationIntervalMillis=<number of milliseconds> - The asynchronous
      replicator runs at a set interval of milliseconds. The default is 1000. The minimum
      is 10. This property is only applicable if replicateAsynchronously=true


    JGroups Replication
    +++++++++++++++++++

	For the Jgroups replication this is done with:
	<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
                            properties="replicateAsynchronously=true, replicatePuts=true,
 							replicateUpdates=true, replicateUpdatesViaCopy=false,
 							replicateRemovals=true,asynchronousReplicationIntervalMillis=1000"/>
    This listener supports the same properties as the RMICacheReplicationFactory.


    JMS Replication
    +++++++++++++++

	For JMS-based replication this is done with:
	<cacheEventListenerFactory
          class="net.sf.ehcache.distribution.jms.JMSCacheReplicatorFactory"
          properties="replicateAsynchronously=true,
                       replicatePuts=true,
                       replicateUpdates=true,
                       replicateUpdatesViaCopy=true,
                       replicateRemovals=true,
                       asynchronousReplicationIntervalMillis=1000"
           propertySeparator=","/>

    This listener supports the same properties as the RMICacheReplicationFactory.
    
    Cluster Bootstrapping
    +++++++++++++++++++++

    Bootstrapping a cluster may use a different mechanism to replication. e.g you can mix
    JMS replication with bootstrap via RMI - just make sure you have the cacheManagerPeerProviderFactory
    and cacheManagerPeerListenerFactory configured.

    There are two bootstrapping mechanisms: RMI and JGroups.

    RMI Bootstrap

    The RMIBootstrapCacheLoader bootstraps caches in clusters where RMICacheReplicators are
    used. It is configured as per the following example:

    <bootstrapCacheLoaderFactory
        class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
        properties="bootstrapAsynchronously=true, maximumChunkSizeBytes=5000000"
        propertySeparator="," />

    The RMIBootstrapCacheLoaderFactory recognises the following optional properties:

    * bootstrapAsynchronously=true|false - whether the bootstrap happens in the background
      after the cache has started. If false, bootstrapping must complete before the cache is
      made available. The default value is true.

    * maximumChunkSizeBytes=<integer> - Caches can potentially be very large, larger than the
      memory limits of the VM. This property allows the bootstraper to fetched elements in
      chunks. The default chunk size is 5000000 (5MB).

    JGroups Bootstrap

    Here is an example of bootstrap configuration using JGroups boostrap:

    <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsBootstrapCacheLoaderFactory"
                                    properties="bootstrapAsynchronously=true"/>

    The configuration properties are the same as for RMI above. Note that JGroups bootstrap only supports
    asynchronous bootstrap mode.                                


    Cache Exception Handling

    By default, most cache operations will propagate a runtime CacheException on failure. An
    interceptor, using a dynamic proxy, may be configured so that a CacheExceptionHandler can
    be configured to intercept Exceptions. Errors are not intercepted.

    It is configured as per the following example:

      <cacheExceptionHandlerFactory class="com.example.ExampleExceptionHandlerFactory"
                                      properties="logLevel=FINE"/>

    Caches with ExceptionHandling configured are not of type Cache, but are of type Ehcache only,
    and are not available using CacheManager.getCache(), but using CacheManager.getEhcache().


    Cache Loader

    A default CacheLoader may be set which loads objects into the cache through asynchronous and
    synchronous methods on Cache. This is different to the bootstrap cache loader, which is used
    only in distributed caching.

    It is configured as per the following example:

        <cacheLoaderFactory class="com.example.ExampleCacheLoaderFactory"
                                      properties="type=int,startCounter=10"/>

    Cache Extension

    CacheExtensions are a general purpose mechanism to allow generic extensions to a Cache.
    CacheExtensions are tied into the Cache lifecycle.

    CacheExtensions are created using the CacheExtensionFactory which has a
    <code>createCacheCacheExtension()</code> method which takes as a parameter a
    Cache and properties. It can thus call back into any public method on Cache, including, of
    course, the load methods.

    Extensions are added as per the following example:

         <cacheExtensionFactory class="com.example.FileWatchingCacheRefresherExtensionFactory"
                             properties="refreshIntervalMillis=18000, loaderTimeout=3000,
                                         flushPeriod=whatever, someOtherProperty=someValue ..."/>

    -->


    <!--
    Mandatory Default Cache configuration. These settings will be applied to caches
    created programmtically using CacheManager.add(String cacheName).

    The defaultCache has an implicit name "default" which is a reserved cache name.
    -->
    <defaultCache
            maxElementsInMemory="1000"
            eternal="false"
            timeToIdleSeconds="1200"
            timeToLiveSeconds="3600"
            overflowToDisk="false"
            maxElementsOnDisk="0"
            diskPersistent="true"
            memoryStoreEvictionPolicy="LRU"
            >
               <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
                properties="replicateAsynchronously=true, 
            replicatePuts=true, 
            replicateUpdates=true,
                replicateUpdatesViaCopy=false, 
            replicateRemovals=true "/>
            </defaultCache>

    <!--
    Sample caches. Following are some example caches. Remove these before use.
    -->

    <!--
    Sample cache named sampleCache1
    This cache contains a maximum in memory of 10000 elements, and will expire
    an element if it is idle for more than 60 minutes and lives for more than
    20 minutes.

    If there are more than 10000 elements it will overflow to the
    disk cache, which in this configuration will go to wherever java.io.tmp is
    defined on your system. On a standard Linux system this will be /tmp"
   
   <cache name="leopardCache" maxElementsInMemory="100000" eternal="false" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="360000" timeToLiveSeconds="360000" memoryStoreEvictionPolicy="LRU" />
 -->
	<cache name="leopardCache"
		    maxElementsInMemory="10000"
		    eternal="false"
		    timeToIdleSeconds="360000" 
		    timeToLiveSeconds="360000" 
		    overflowToDisk="false">
		    <cacheEventListenerFactory
		        class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
		        properties="replicateAsynchronously=true, replicatePuts=true, 
			    replicateUpdates=true,replicateUpdatesViaCopy=false, replicateRemovals=true "/>
	</cache>
		 

 
    
</ehcache>

实现

        List dsConfList = ContextConfig.getInstance().getListConf("datasource");
        IBean tmpBean = null;
        DataSource dsInst = null;
        for (Iterator<IBean> iterator = dsConfList.iterator(); iterator.hasNext();) {
            tmpBean = iterator.next();
            String dsId = (String) tmpBean.get("id");
            String dsName = (String) tmpBean.get("datasource");
            String tmpStr = (String) tmpBean.get("default");

            boolean isDefault = tmpStr != null && tmpStr.equalsIgnoreCase("true") ? true : false;

            dsInst = lookDS(dsName);
            if (dsInst != null) {
                dsMap.put(dsName, new DataSource(dsName, dsInst));
                if (isDefault) {
                    defDS = dsName;
                }
            }
        }

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wespten

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值