JAVA中缓存的实现

来源:互联网 发布:java的todo 编辑:程序博客网 时间:2024/04/30 14:56
JAVA中缓存的实现             2010-04-23 10:39package com.tq.pubsecurity.cache;import java.io.Serializable;import net.sf.ehcache.Cache;import net.sf.ehcache.CacheManager;import net.sf.ehcache.Element;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/*** @description 缓存管理*/public class CacheManageProxy {private static final Log logger = LogFactory.getLog(CacheManageProxy.class);private Cache cache = null;private CacheManager cacheManager;public CacheManageProxy(CacheManager cacheManager) {   this.cacheManager = cacheManager;   this.cache = cacheManager.getCache("longTimeCache");}   /*** 缓存存储结构* @param {Class} 类名* @param {String} 方法名* @param {String} 参数集字符串* @param {Serializable} 序列化结果集* @return null* */public void putValue(Class cls, String method, String key,    Serializable value) {   String cacheKey = new StringBuffer(cls.toString()).append(":").append(     method).append(":").append(key).toString();   Element element = new Element(cacheKey, value);   logger.debug("放入cache:" + cacheKey);   this.cache.put(element);}/*** 取出缓存* @param {Class} 类名* @param {String} 方法名* @param {String} 参数集字符串* @return {Serializable} 序列化结果集* */public Serializable getValue(Class cls, String method, String key) {   try {    String cacheKey = new StringBuffer(cls.toString()).append(":")      .append(method).append(":").append(key).toString();    Element element = this.cache.get(cacheKey);    if (element == null)     return null;    logger.debug("从cache中取:" + cacheKey);    return element.getValue();   } catch (Exception e) {    return null;   }}    //清空所有缓存public void clearAllCache() {   String[] cache = cacheManager.getCacheNames();   for (int i = 0; i < cache.length; i++) {    try {     cacheManager.getCache(cache[i]).removeAll();    } catch (Exception e) {    }   }}}

原创粉丝点击