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();
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文档
productLineCode
LEOPARD
1
jdbc/oracle
cache.xml
10000
3600000
false
leopard_ehcache.xml
实现
List dsConfList = ContextConfig.getInstance().getListConf("datasource");
IBean tmpBean = null;
DataSource dsInst = null;
for (Iterator 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;
}
}
}