实现缓存功能

1、缓存
 CacheBean.getIntance();
 package com.comName.epg.cache.aop;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.comName.epg.cache.manager.IEpgCacheManager;

/**
 * 内容摘要:将缓存操作类注册
 * 编码作者:
 * 完成日期:
 */
public class CacheBean
{
    private  static Map<String, IEpgCacheManager> map = new HashMap<String, IEpgCacheManager>();
    
    private static final Logger logger = Logger.getLogger(CacheBean.class);
    
    private static CacheBean instance = new CacheBean();

    // 注册需要处理的拦截处理类

    /**
     * resourceDao拦截类常量
     */
    public static final String CHANNEL_DAO = "com.comName.epg.dao.tv.IChannelDao";

    /**
     * programDao拦截类常量
     */
    public static final String PROGRAM_DAO = "com.comName.epg.dao.tv.IProgramDao";

    /**
     * catalogDao拦截类常量
     */
    public static final String CATALOG_DAO = "com.comName.epg.dao.mod.ICatalogDao";

    /**
     * productOfferingDao拦截类常量
     */
    public static final String PRODUCT_OFFERING_DAO = "com.comName.epg.dao.mod.IProductOfferingDao";

    /**
     * resourceDao拦截类常量
     */
    public static final String RESOURCE_DAO = "com.comName.epg.dao.mod.IResourceDaoNew";

    /**
     * parameterDao拦截类常量
     */
    public static final String PARAMETER_DAO = "com.comName.epg.dao.parameter.IParameterDao";

    /**
     * com.comName.aaa.dao.impl.jdbc2.ChannelDao拦截常量
     */
    public static final String WSCHANNEL_DAO = "com.comName.aaa.dao.IChannelDao";

    /**
     * com.comName.aaa.dao.impl.jdbc2.ChannelDao拦截常量
     */
    // public static final String WSAUTHORITY_DAO =
    // "com.comName.aaa.dao.IAuthorityDao";
    /**
     * com.comName.aaa.dao.impl.jdbc2.ChannelDao拦截常量
     */
    public static final String WSCOMMON_DAO = "com.comName.aaa.dao.ICommonDao";

    /**
     * com.comName.aaa.dao.impl.jdbc2.ProductDao拦截常量
     */
    public static final String WSPRODUCT_DAO = "com.comName.aaa.dao.IProductDao";

    public static final String USER_DAO = "com.comName.aaa.dao.IUserDao";
    
    public static final String PROGRAMEXTRAINFO_DAO = "com.comName.epg.dao.tv.IProgramExtraInfoDao";
    
    public static IEpgCacheManager monitorCache;
    
    private static IEpgCacheManager sessionsCache;
    
    
    /**
     * 私有构造
     */
    private CacheBean()
    {
        init();
    }

    /**
     * 初始化
     */
    public synchronized static void init()
    {
        // 将dao拦截处理类在此处注册
        map.put(CHANNEL_DAO, new ChannelCache());
        map.put(PROGRAM_DAO, new ProgramCache());
        map.put(PARAMETER_DAO, new ParameterCache());
        map.put(CATALOG_DAO, new CatalogCache());
        map.put(PRODUCT_OFFERING_DAO, new ProductOfferingCache());
        map.put(PROGRAMEXTRAINFO_DAO, new ProgramExtraInfoCache());
        // 此处使用同一个缓存
        ResourceCache resourceCache = new ResourceCache();
        map.put(RESOURCE_DAO, resourceCache);
        map.put(WSPRODUCT_DAO, resourceCache);//addVodPopularForCache
        
        monitorCache=new MonitorCache();
        sessionsCache=new SessionsCache();
        
//        map.put(WSCHANNEL_DAO, new WsChannelCache());
//        map.put(WSCOMMON_DAO, new WsCommonCache());
        
        
        // map.put(WSAUTHORITY_DAO, new WsAuthorityCache());
//        map.put(USER_DAO, new UserCache());
    }
    public static IEpgCacheManager getMonitorCache()
    {
        return monitorCache;
    }
    
    public static IEpgCacheManager getSessionsCache()
    {
        return sessionsCache;
    }
    

    /**
     * 获取实例
     * @return
     */
    public static CacheBean getIntance()
    {
        return instance;
    }

    /**
     * 获取缓存处理类实例
     * @param name
     * @return
     */
    public IInvoke getInvokeBean(String name)
    {
        return (IInvoke) map.get(name);
    }

    /**
     * 获取缓存处理类实例
     * @param name
     * @return
     */
    public IEpgCacheManager getManageBean(String name)
    {
        return (IEpgCacheManager) map.get(name);
    }

    public static Map<String, IEpgCacheManager> getMap()
    {
        return map;
    }
    
    public static void celarAllCache()
    {
        logger.info("--------开始清除所有缓存----------");
        Set<Entry<String, IEpgCacheManager>> entrySet = map.entrySet();
        for (Entry<String, IEpgCacheManager> entry : entrySet)
        {
            entry.getValue().removeAll();
        }
        logger.info("--------清除缓存完毕----------");
    }
}

package com.comName.epg.cache.manager;

import java.util.List;

/**
 * 内容摘要:缓存管理接口
 * 编码作者:
 * 完成日期:
 */
public interface IEpgCacheManager
{
    public void put(String key, Object value);
    /**
     * 实现功能:清空所有缓存
     */
    public void removeAll();

    /**
     * 实现功能:按key值清空缓存
     */
    public boolean removeByKey(String key);

    /**
     * 实现功能:按模糊key值清空缓存
     * 如:removeByFuzzyKey("Channel_",IEpgCacheManager.START_WITH)将删除缓存中所有以"Channel_"开头的key对应的缓存数据
     * @param key 查询参数
     * @param pattern 可选参数为:START_WITH,ENDS_WITH,INCLUDE
     * @return 缓存数据删除个数
     */
    public int removeByFuzzyKey(String key, int pattern);

    /**
     * 实现功能:按表达式key值清空缓存
     * 如:removeByPatternKey("Channel_\\w*")将删除缓存中所有以"Channel_"开头的key对应的缓存数据
     * @param patternKey 表达式字符串
     * @return 缓存数据删除个数
     */
    public int removeByPatternKey(String patternKey);

    /**
     * 实现功能:获得所有的缓存对象的key
     */
    public List getAllKeys();

    /**
     * 实现功能:根据缓存对象的key获取缓存对象
     */
    public Object getObjectByKey(String key);

    public void flush();
    
    /**
     * 缓存中的key值以参数字符串开头
     */
    public static final int START_WITH = 1;

    /**
     * 缓存中的key值以参数字符串结尾
     */
    public static final int ENDS_WITH = 2;

    /**
     * 缓存中的key值包含参数字符串中的字符
     */
    public static final int INCLUDE = 3;
    
    public int getSize();
}


package com.comName.epg.cache.aop;

import org.aopalliance.intercept.MethodInvocation;

import com.comName.epg.model.Catalog;

/**
 * 内容摘要:商品查询dao拦截实现
 * 编码作者:
 * 完成日期:
 */
public class CatalogCache extends AbstractCache
{

    private static final String service_code = "ServiceCode_";

    /**
     * 通过catalog对象的id保存数据的前缀
     */
    public static final String CATALOG_PRE = "CATALOG_";

    /**
     * 通过catalog对象的serviceCode保存数据的前缀
     */
    public static final String CATALOG_SERVICE_CODE_PRE = CATALOG_PRE + service_code;

    /**
     * 保存子栏目List的前缀
     */
    public static final String SUB_CATALOG_PRE = CATALOG_PRE + symbol_objs;

    /**
     * 根据上架ID查询栏目信息,保存至缓存
     */
    public static final String CATALOG_RESOURCE = "catalog_resource_";

    protected CatalogCache()
    {
        super("CatalogCache");
    }

    protected MethodProcess parseMethodProcess(MethodInvocation invocation)
    {
        MethodProcess process = new MethodProcess();
        String methodName = invocation.getMethod().getName();
        Object[] argument = invocation.getArguments();

        if (querySubCatalogs.equals(methodName))
        {
            process.setMethodType(MethodProcessType.getObjectListByParamType);
            process.setCacheKey(SUB_CATALOG_PRE + String.valueOf(argument[0]));
            process.setSaveEmptyList(true);
            //TODO 增加子栏目时刷新
        }
        else if (getCatalog.equals(methodName))
        {
            process.setMethodType(MethodProcessType.getObjectByIdType);
            process.setCacheKey(CATALOG_PRE + String.valueOf(argument[0]));
        }
        else if (queryCatalogByServiceCode.equals(methodName))
        {
            process.setMethodType(MethodProcessType.getObjectByIdType);
            process.setCacheKey(CATALOG_SERVICE_CODE_PRE + String.valueOf(argument[0]));
            // serviceCode对应的key,保存的是栏目的缓存key
            process.setCacheObjectReference(true);
        }
//        else if (queryCatalogByCatalogResourceId.equals(methodName))
//        {
//            process.setMethodType(MethodProcessType.getObjectByIdType);
//            process.setCacheKey(CATALOG_PRE + CATALOG_RESOURCE + String.valueOf(argument[0]));
//        }
        //add by sunwen
        else if(queryCatalogIdForRes.equals(methodName)){
            //根据资源找上架栏目id  栏目上架时/下架时 刷新
            process.setMethodType(MethodProcessType.getObjectListByParamType);
            process.setCacheKey(queryCatalogIdForRes+"_"+argument[0]);
            process.setCacheSingleResult(false);
            process.setSaveEmptyList(true);
        }
        return process;
    }

    protected String getModelKey(Object obj, MethodInvocation invocation)
    {
        return CATALOG_PRE + String.valueOf(((Catalog) obj).getId());
    }

    private static final String querySubCatalogs = "querySubCatalogs";

    private static final String getCatalog = "getCatalog";

    private static final String queryCatalogByServiceCode = "queryCatalogByServiceCode";

//    private static final String queryCatalogByCatalogResourceId = "queryCatalogByCatalogResourceId";
    
    public static final String queryCatalogIdForRes="queryCatalogIdForRes";
}

package com.comName.epg.cache.aop;

import org.aopalliance.intercept.MethodInvocation;

/**
 * 内容摘要:dao拦截器接口
 * 编码作者:
 * 完成日期:
 */
public interface IInvoke
{
    /**
     * 实现功能:处理拦截器动作
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    public Object invoke(MethodInvocation invocation) throws Throwable;
}

package com.comName.epg.cache.aop;

public final class MethodProcess
{
    /**
     * 缓存key,或单个缓存对象的key前缀,默认值为null,此时不会拦截
     */
    private String cacheKey = null;

    /**
     * 方法类型
     */
    private int methodType = MethodProcessType.typeUndefined;

    /**
     * 判断getObjectListById方法,获取的对象集合后,是否缓存单个集合对象
     */
    private boolean isCacheSingleResult = true;
    
    /**
     * getObjectById方法,不是通过ID缓存的数据,此时是否缓存对象的key值
     * 默认为不缓存,直接保存原数据。为true时,缓存对象和对象的缓存key
     */
    private boolean isCacheObjectReference = false;
    
    /**
     * getObjectListByParamType
     * 是否保存空的集合
     */
    private boolean isSaveEmptyList=false;
    
    public int getMethodType()
    {
        return methodType;
    }

    public void setMethodType(int methodType)
    {
        this.methodType = methodType;
    }

    public String getCacheKey()
    {
        return cacheKey;
    }

    public void setCacheKey(String cacheKey)
    {
        this.cacheKey = cacheKey;
    }

    public boolean isCacheSingleResult()
    {
        return isCacheSingleResult;
    }

    public void setCacheSingleResult(boolean isCacheSingleResult)
    {
        this.isCacheSingleResult = isCacheSingleResult;
    }

    public boolean isCacheObjectReference()
    {
        return isCacheObjectReference;
    }

    public void setCacheObjectReference(boolean isCacheObjectReference)
    {
        this.isCacheObjectReference = isCacheObjectReference;
    }

    public boolean isSaveEmptyList()
    {
        return isSaveEmptyList;
    }

    public void setSaveEmptyList(boolean isSaveEmptyList)
    {
        this.isSaveEmptyList = isSaveEmptyList;
    }

}

package com.comName.epg.model;

import java.io.Serializable;
import java.util.List;

public class Catalog implements Serializable
{

    private Integer id;

    private String name;

    private String serviceCode;

    private String description;

    private Integer ordinal;

    private Integer parentCatalogId;

    private List<Poster> posters; // 海报路径

    private int recommendCount;

    private int resourceCount;// 栏目下的资源总数

    private Integer saleType;

    private String resourceId;

    private String goodsId;
    
    private List<Catalog> subCatalogList;
    
    private List<ProductResource> resourceList;
    
    private Integer isMonthColOnePay=1;
    
    public Integer getIsMonthColOnePay()
    {
        return isMonthColOnePay;
    }

    public void setIsMonthColOnePay(Integer isMonthColOnePay)
    {
        this.isMonthColOnePay = isMonthColOnePay;
    }

    public List<ProductResource> getResourceList()
    {
        return resourceList;
    }

    public void setResourceList(List<ProductResource> resourceList)
    {
        this.resourceList = resourceList;
    }

    public List<Catalog> getSubCatalogList()
    {
        return subCatalogList;
    }

    public void setSubCatalogList(List<Catalog> subCatalogList)
    {
        this.subCatalogList = subCatalogList;
    }

    public String getGoodsId()
    {
        return goodsId;
    }

    public void setGoodsId(String goodsId)
    {
        this.goodsId = goodsId;
    }

    public String getResourceId()
    {
        return resourceId;
    }

    public void setResourceId(String resourceId)
    {
        this.resourceId = resourceId;
    }

    public Integer getSaleType()
    {
        return saleType;
    }

    public void setSaleType(Integer saleType)
    {
        this.saleType = saleType;
    }

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public String getName()
    {
        return GBKfilter.filter(name);
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getServiceCode()
    {
        return serviceCode;
    }

    public void setServiceCode(String serviceCode)
    {
        this.serviceCode = serviceCode;
    }

    public String getDescription()
    {
        return GBKfilter.filter(description);
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public Integer getOrdinal()
    {
        return ordinal;
    }

    public void setOrdinal(Integer ordinal)
    {
        this.ordinal = ordinal;
    }

    public Integer getParentCatalogId()
    {
        return parentCatalogId;
    }

    public void setParentCatalogId(Integer parentCatalogId)
    {
        this.parentCatalogId = parentCatalogId;
    }

    public List<Poster> getPosters()
    {
        return posters;
    }

    public void setPosters(List<Poster> posters)
    {
        this.posters = posters;
    }

    public int getRecommendCount()
    {
        return recommendCount;
    }

    public void setRecommendCount(int recommendCount)
    {
        this.recommendCount = recommendCount;
    }

    public int getResourceCount()
    {
        return resourceCount;
    }

    public void setResourceCount(int resourceCount)
    {
        this.resourceCount = resourceCount;
    }

}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.comName.common;

/**
 *
 * @author 903274
 */
public class AppRuntimeException extends RuntimeException {

    private EnumPower errorInfo = null;
    
    private String errorCode;
    
    private String errorMessage;
    
    public String getErrorMessage()
    {
        return errorMessage;
    }



    public String getErrorCode() {
        return this.errorCode;
    }
    
    private void setErrorMessage(String errorCode, String errorMessage)
    {
        this.errorCode=errorCode;
        this.errorMessage=errorMessage;
    }
    
    public AppRuntimeException(String errorCode, String message) {
        super(message);
        setErrorMessage(errorCode, message);
    }
    
    
    public AppRuntimeException(EnumPower errorInfo) {
        super(errorInfo.toString());
        this.errorInfo = errorInfo;
        setErrorMessage(errorInfo.getCode(), errorInfo.getTitle());
    }

    public AppRuntimeException(EnumPower errorInfo, Throwable cause) {
        super(errorInfo.toString(), cause);
        this.errorInfo = errorInfo;
        setErrorMessage(errorInfo.getCode(), errorInfo.getTitle());
    }

    public AppRuntimeException(AppRuntimeException appException) {
        this(appException.getErrorInfo(), appException.getCause());
    }
    public AppRuntimeException(String appException){       
        super(appException);
    }

    public EnumPower getErrorInfo() {
        return this.errorInfo;
    }

}


package com.comName.common;


import java.util.*;

import com.comName.common.EnumPower;

/**
 * <p>Title: tvboss</p>
 *
 * <p>Description: 业务运营支撑系统</p>
 *
 * <p>Copyright: Copyright (c) </p>
 *
 * <p>Company: clong</p>
 *
 * @author
 * @version 3.0
 */
public enum CommInfo implements EnumPower {
    SUCCESS("0000", "成功"),
    FAILURE("0001", "失败"),    
    VERSION_INVALID("0002", "版本信息无效"),
    PARA_VALUE_IS_NULL("0003", "参数值为空"),
    PARA_PATTERN_INVALID("0004", "参数格式不正确"),     
    UNKONWN_HOST("0005", "未找到目标主机,请检查网络配置"),
    UNKONWN_PROT("0006", "服务未启动,或端口有改动,请检查网络配置"),
    SOCKET_TIME_OUT("0007", "网络连接超时,请检查网络"),
    IO_EXCEPTION("0008", "网络通讯异常,请检查网络"),   
    BOSS_SERVER_RUN_WRONG("0009","系统忙,请稍后再试!BOSS服务运行异常"),  
    NO_DATA("0010","数据不存在"),
    DATABASE_EXCEPTION("0011","数据库异常"),
    JAXB_EXCEPTION("0012","文档解析异常"),
    WRONG_DTO("0013", "传输对象有误"),   
    CLONE_ERROR("0014", "克隆对象出错"),
    SYSTEM_PARAMETER("0015", "查找系统参数失败"),
    START_TIME_IS_NULL("0016", "起始播放时间不能为空"),
    UNKNOWN("0099","未知异常"),    
    INVALID_CACHE("0018", "缓存异常"),
    INVALID_PROGRAM("0019", "节目单无效"),
    INVALID_CHANNEL("0020", "频道无效"),
    DEFAULT_ERROR("-1", "网络繁忙,请稍后再试"),
    SUCCESS_ZERO("0", "成功")
    ;
       ;

    private String code = null;
    private String title = null;
    private static Hashtable<String, CommInfo> aliasEnums;

    CommInfo(String code, String title) {
        this.init(code, title);
    }

    @SuppressWarnings("unchecked")
    private void init(String code, String title) {
        this.code = code;
        this.title = title;
        synchronized (this.getClass()) {
            if (aliasEnums == null) {
                aliasEnums = new Hashtable();
            }
        }
        aliasEnums.put(code, this);
        aliasEnums.put(title, this);
    }

    public static CommInfo valueOfAlias(String alias) {
        return aliasEnums.get(alias);
    }

    public static CommInfo valueOfAlias(char alias) {
        return aliasEnums.get(String.valueOf(alias));
    }

    public String getCode() {
        return this.code;
    }

    public char getChar() {
        return this.code.charAt(0);
    }

    public String getTitle() {
        return this.title;
    }

    /**
     * 信息描述
     * @return String
     */
    @Override
    public String toString() {
        return this.getTitle() + "〔信息代码:" + this.getCode() + "〕";
    }
}


/*
 * EnumObject.java
 *
 * Created on 2007-8-26, 20:40:49
 *
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.comName.common;

/**
 *
 * @author Administrator
 */
public interface EnumPower {
    public String getCode();
    
    public char getChar();

    public String getTitle();

    public String name();

    public int ordinal();

    public String toString();
}

package com.comName.epg.cache.manager;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.Statistics;
import net.sf.ehcache.cluster.CacheCluster;
import net.sf.ehcache.cluster.ClusterNode;
import net.sf.ehcache.cluster.ClusterScheme;
import net.sf.ehcache.cluster.ClusterTopologyListener;

import org.apache.log4j.Logger;

/**
 * 内容摘要:ehcach缓存封装
 * 编码作者:
 * 完成日期:
 */
public class EpgCache implements IEpgCache
{
    private static final Logger log = Logger.getLogger(EpgCache.class);
    // ehcache缓存实例
    private static CacheManager manager;

    // ehcache缓存的一个具体的缓存块
    private Cache cache;
    
    private static  boolean cacheStatus=true;
    
    static {
        init();
    }
    
    private static synchronized void init()
    {
            manager=CacheManager.getInstance();
        
    }
    
    public static synchronized void restart()throws Exception
    {
        if(manager!=null)
        {
            manager.shutdown();
        }
        init();
    }
 
    
    public static boolean getCacheStatus()
    {
        return cacheStatus;
    }

    public static void setCacheStatus(boolean cacheStatus)
    {
            EpgCache.cacheStatus = cacheStatus;
    }

    /**
     * 构造函数
     * @param name
     */
    public EpgCache(String name)
    {
        cache = manager.getCache(name);
    }

    /**
     * 实现功能:将对象从缓存中取出
     * @param key
     * @return
     */
    public Object get(String key)
    {
        Element e = cache.getQuiet(key);
        if (e != null)
        {
            return e.getObjectValue();
        }
        return null;
    }

    /**
     * 实现功能:获得所有的缓存对象的key
     */
    public List getAllKeys()
    {
        return cache.getKeys();
    }

    /**
     * 实现功能:将对象加入缓存
     * @param key
     * @param value
     */
    public void put(String key, Object value)
    {
        //cache.remove(key);
//        cache.putQuiet(new Element(key, value));
        cache.put(new Element(key, value));
    }

    /**
     * 实现功能:清空缓存中所有数据
     */
    public void removeAll()
    {
        cache.removeAll();
    }

    /**
     * 按对应的key值清空对应缓存
     */
    public boolean removeByKey(String key)
    {
        return cache.removeQuiet(key);
    }

    /**
     * 实现功能:按模糊key值清空缓存
     * 如:removeByFuzzyKey("Channel_",IEpgCacheManager.START_WITH)将删除缓存中所有以"Channel_"开头的key对应的缓存数据
     * @param key 查询参数
     * @param pattern 可选参数为:START_WITH,ENDS_WITH,INCLUDE
     * @return 缓存数据删除个数
     */
    public int removeByFuzzyKey(String key, int pattern)
    {
        // 记录删除缓存的个数
        int count = 0;
        // 得到所有的key
        List keyList = cache.getKeys();
        switch (pattern)
        {
            // 以匹配字符串开头
            case IEpgCacheManager.START_WITH:
                count = removeStartsWith(keyList, key);
                break;
            // 以匹配字符串结尾
            case IEpgCacheManager.ENDS_WITH:
                count = removeEndsWith(keyList, key);
                break;
            // 包含匹配字符串
            case IEpgCacheManager.INCLUDE:
                count = removeInclude(keyList, key);
                break;
            // 都不是
            default:
                break;
        }
        return count;
    }

    /**
     * 删除以指定字符开头的key在缓存中的数据
     * @param keyList
     * @param key
     * @return
     */
    private int removeStartsWith(List keyList, String key)
    {
        int count = 0;
        for (Object keyTemp:keyList)
        {
//            String keyTemp = (String) keyList.get(i);
            if (keyTemp != null && ((String)keyTemp).startsWith(key))
            {
                cache.removeQuiet(keyTemp);
                count++;
            }
        }
        return count;
    }

    /**
     * 删除以指定字符结尾的key在缓存中的数据
     * @param keyList
     * @param key
     * @return
     */
    private int removeEndsWith(List keyList, String key)
    {
        int count = 0;
        for (int i = 0; i < keyList.size(); i++)
        {
            String keyTemp = (String) keyList.get(i);
            if (keyTemp != null && keyTemp.endsWith(key))
            {
                cache.removeQuiet(keyTemp);
                count++;
            }
        }
        return count;
    }

    /**
     * 删除以指定字符包含在key中在缓存的数据
     * @param keyList
     * @param key
     * @return
     */
    private int removeInclude(List keyList, String key)
    {
        int count = 0;
        for (int i = 0; i < keyList.size(); i++)
        {
            String keyTemp = (String) keyList.get(i);
            if (keyTemp != null && keyTemp.indexOf(key) != -1)
            {
                cache.removeQuiet(keyTemp);
                count++;
            }
        }
        return count;
    }

    /**
     * 实现功能:按表达式key值清空缓存
     * 如:removeByPatternKey("Channel_\\w*")将删除缓存中所有以"Channel_"开头的key对应的缓存数据
     * @param patternKey 表达式字符串
     * @return 缓存数据删除个数
     */
    public int removeByPatternKey(String patternKey)
    {
        // 记录删除缓存的个数
        int count = 0;
        // 得到所有的key
        List keyList = cache.getKeys();
        Pattern pattern = Pattern.compile(patternKey);
        Matcher matcher = null;
        for (int i = 0; i < keyList.size(); i++)
        {
            String keyTemp = (String) keyList.get(i);
            // 判断key值是否匹配正则表达式
            matcher = pattern.matcher(keyTemp);
            if (matcher.matches())
            {
                cache.removeQuiet(keyTemp);
                count++;
            }
        }
        return count;
    }
    
    public Statistics getStatistics()
    {
        return cache.getStatistics();
    }
    
    @Override
    public void flush()
    {
        cache.flush();
    }
    
    @Override
    public int getSize()
    {
       return cache.getSize();
    }
    
    @Deprecated
    private static void addTopologyListener()
    {
        CacheCluster cluster =manager.getCluster(ClusterScheme.TERRACOTTA);
        cluster.addTopologyListener(new ClusterTopologyListener()
        {
            public void nodeJoined(ClusterNode node)
            {
                setCacheStatus(true);
                log.info(node + " joined");
            }
            public void clusterRejoined(ClusterNode node, ClusterNode newNode)
            {
                setCacheStatus(true);
                log.info(node + " rejoined the cluster as " + newNode);
            }
            public void clusterOnline(ClusterNode node)
            {
                setCacheStatus(true);
                log.info(node + " enabled");
            }
            public void nodeLeft(ClusterNode node)
            {
                setCacheStatus(false);
                log.error(node + " left");
            }

            public void clusterOffline(ClusterNode node)
            {
                setCacheStatus(false);
                log.error(node + " disabled");
            }

        });
    }

    public Cache getCache()
    {
        return cache;
    }
    
}

package com.comName.epg.cache.manager;

import java.util.List;

/**
 * 内容摘要:缓存数据接口
 * 编码作者:
 * 完成日期:
 */
public interface IEpgCache
{
    /**
     * 实现功能:将对象加入缓存
     * @param key
     * @param value
     */
    public void put(String key, Object value);

    /**
     * 实现功能:将对象从缓存中取出
     * @param key
     * @return
     */
    public Object get(String key);

    /**
     * 实现功能:获得所有的缓存对象的key
     */
    public List getAllKeys();

    /**
     * 实现功能:清空缓存中所有数据
     */
    public void removeAll();

    /**
     * 实现功能:按对应的key值清空对应缓存
     */
    public boolean removeByKey(String key);

    /**
     * 实现功能:按模糊key值清空缓存
     * 如:removeByFuzzyKey("Channel_",IEpgCacheManager.START_WITH)将删除缓存中所有以"Channel_"开头的key对应的缓存数据
     * @param key 查询参数
     * @param pattern 可选参数为:START_WITH,ENDS_WITH,INCLUDE
     * @return 缓存数据删除个数
     */
    public int removeByFuzzyKey(String key, int pattern);

    /**
     * 实现功能:按表达式key值清空缓存
     * 如:removeByPatternKey("Channel_\\w*")将删除缓存中所有以"Channel_"开头的key对应的缓存数据
     * @param patternKey 表达式字符串
     * @return 缓存数据删除个数
     */
    public int removeByPatternKey(String patternKey);
    
    public void flush();
    
    
    int getSize();
    
}

package com.comName.epg.cache.manager;

import java.util.List;

import org.apache.log4j.Logger;

import com.comName.common.cache.Cache;
import com.comName.common.cache.CacheManager;

public class Xmemcache implements IEpgCache
{
    private static Cache cache = CacheManager.getInstance().getCache();
    
    private static final Logger log = Logger.getLogger(Xmemcache.class);
    
    public Object get(String key)
    {
        return cache.get(key);
    }

    public List getAllKeys()
    {
        return null;
    }

    public void flush()
    {
      cache.flushAll();        
    }
    
    public void put(String key, Object value)
    {
        boolean flag = cache.set(key, value);
        if(!flag)
        {
         log.warn("put cache fail:"+key+" value="+value);   
        }else{
            log.debug("put cache success:"+key+" value="+value);   
        }
    }

    public void removeAll()
    {
        cache.flushAll();
    }

    public int removeByFuzzyKey(String key, int pattern)
    {
        return 0;
    }

    public boolean removeByKey(String key)
    {
        try
        {
            return cache.delete(key);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    public int removeByPatternKey(String patternKey)
    {
        //TODO
        return 0;
    }

    public boolean getCacheStatus()
    {
        //TODO
        return true;
    }

    @Override
    public int getSize()
    {
        //TODO
        return 0;
    }

}

// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) radix(10) lradix(10)
// Source File Name:   Cache.java

package com.comName.common.cache;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;

public interface Cache
{

    public abstract boolean add(String s, Object obj);

    public abstract void addServer(String s, int i, int j);

    public abstract boolean append(String s, Object obj);

    public abstract boolean delete(String s);

    public abstract void flushAll();

    public abstract void flushAll(InetSocketAddress inetsocketaddress);

    public abstract boolean isShutdown();

    public abstract void shutdown()
        throws IOException;

    public abstract Map stats(InetSocketAddress inetsocketaddress);

    public abstract void removeServer(String s);

    public abstract boolean replace(String s, Object obj);

    public abstract boolean set(String s, Object obj);

    public abstract Object get(String s);

    public abstract Map getStats();
}

// Messages from Jad:
// The class file version is 50.0 (only 45.3, 46.0 and 47.0 are supported)
//

// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) radix(10) lradix(10)
// Source File Name:   CacheManager.java

package com.comName.common.cache;

import com.comName.common.cache.config.ConfigFileTool;
import com.comName.common.cache.xmemcache.CacheImp;
import java.io.IOException;
import java.io.PrintStream;
import net.rubyeye.xmemcached.*;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;
import org.apache.log4j.Logger;

// Referenced classes of package com.comName.common.cache:
//            Cache

public class CacheManager
{

    private CacheManager()
    {
        cache = null;
        try
        {
            init();
        }
        catch(Exception ex)
        {
            log.error((new StringBuilder("\u521D\u59CB\u5316\u7F13\u5B58\u5931\u8D25\uFF01")).append(ex).toString());
            ex.printStackTrace();
        }
    }

    public static CacheManager getInstance()
    {
        return instance;
    }

    private synchronized void init()
        throws IOException
    {
        try
        {
            ConfigFileTool config = new ConfigFileTool();
            String servers = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheServers");
            String connPoolSize = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheConnPoolSize");
            String weight = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheWeight");
            String getExp = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheExp");
            String cacheOpTimeout = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheOpTimeout");
            String failureModeFlag = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheFailureMode");
            String setTimeOutFile = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheSetTimeOut");
            String getTimeOutFile = config.getProperty(ConfigFileTool.SYSCONFIG, "memcacheGetTimeOut");
            System.out.println((new StringBuilder("\u7F13\u5B58\u914D\u7F6E\u5982\u4E0B\uFF1Aservers=")).append(servers).toString());
            log.info((new StringBuilder("\u7F13\u5B58\u914D\u7F6E\u5982\u4E0B\uFF1Aservers=")).append(servers).toString());
            log.info((new StringBuilder("\u7F13\u5B58\u914D\u7F6E\u5982\u4E0B\uFF1AconnPoolSize=")).append(connPoolSize).toString());
            log.info((new StringBuilder("\u7F13\u5B58\u914D\u7F6E\u5982\u4E0B\uFF1AcacheOpTimeout=")).append(cacheOpTimeout).toString());
            setTimeOut = Long.valueOf(Long.parseLong(setTimeOutFile));
            getTimeOut = Long.valueOf(Long.parseLong(getTimeOutFile));
            exp = Integer.valueOf(getExp);
            String ininal[] = weight.split(" ");
            int serverWeight[] = new int[ininal.length];
            for(int i = 0; i < ininal.length; i++)
                serverWeight[i] = Integer.parseInt(ininal[i]);

            MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddressMap(servers), serverWeight);
            builder.setSessionLocator(new KetamaMemcachedSessionLocator());
            if(failureModeFlag.equals("Y"))
                builder.setFailureMode(true);
            else
                builder.setFailureMode(false);
            builder.setConnectionPoolSize((new Integer(connPoolSize)).intValue());
            MemcachedClient memcachedClient = builder.build();
            memcachedClient.setOpTimeout((new Long(cacheOpTimeout)).longValue());
            memcachedClient.setMergeFactor(50);
            memcachedClient.setOptimizeMergeBuffer(false);
            memcachedClient.setConnectTimeout(2000L);
            cache = new CacheImp(memcachedClient);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public Cache getCache()
    {
        return cache;
    }

    public void setCache(Cache cache)
    {
        this.cache = cache;
    }

    public static Long getSetTimeOut()
    {
        return setTimeOut;
    }

    public static void setSetTimeOut(Long setTimeOut)
    {
        setTimeOut = setTimeOut;
    }

    public static Long getGetTimeOut()
    {
        return getTimeOut;
    }

    public static void setGetTimeOut(Long getTimeOut)
    {
        getTimeOut = getTimeOut;
    }

    public static Integer getExp()
    {
        return exp;
    }

    public static void setExp(Integer exp)
    {
        exp = exp;
    }

    private static Logger log = Logger.getLogger(com/comName/common/cache/CacheManager);
    private static CacheManager instance = new CacheManager();
    private Cache cache;
    private static Long setTimeOut;
    private static Long getTimeOut;
    private static Integer exp;

}

// Messages from Jad:
// The class file version is 50.0 (only 45.3, 46.0 and 47.0 are supported)
//

// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) radix(10) lradix(10)
// Source File Name:   ConfigFileTool.java

package com.comName.common.cache.config;

import java.util.*;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

public class ConfigFileTool
{

    public ConfigFileTool()
    {
    }

    protected synchronized void setProperty(String configName, String key, String value)
    {
        PropertiesConfiguration targetconfig = (PropertiesConfiguration)configMap.get(configName);
        targetconfig.setProperty(key, value);
        try
        {
            targetconfig.save();
        }
        catch(ConfigurationException e)
        {
            e.printStackTrace();
        }
    }

    public String getProperty(String configName, String key)
    {
        PropertiesConfiguration targetConfig = (PropertiesConfiguration)configMap.get(configName);
        String value = null;
        if(targetConfig.containsKey(key))
        {
            Object property = targetConfig.getProperty(key);
            if(property instanceof List)
            {
                List propertylist = (List)property;
                return (String)propertylist.get(0);
            }
            value = (String)targetConfig.getProperty(key);
        }
        return value;
    }

    protected List getKeys(String configName, String prefix)
    {
        PropertiesConfiguration targetConfig = (PropertiesConfiguration)configMap.get(configName);
        List prefixlist = new ArrayList();
        for(Iterator it = targetConfig.getKeys(); it.hasNext();)
        {
            String configKey = (String)it.next();
            if(configKey.startsWith(prefix))
                prefixlist.add(configKey);
        }

        return prefixlist;
    }

    protected Map getProperties(String configName)
    {
        PropertiesConfiguration targetConfig = (PropertiesConfiguration)configMap.get(configName);
        Map propertymap = new HashMap();
        String key;
        for(Iterator it = targetConfig.getKeys(); it.hasNext(); propertymap.put(key, targetConfig.getProperty(key)))
            key = (String)it.next();

        return propertymap;
    }

    public static String SYSCONFIG;
    public static String lOG4J;
    private static Logger log;
    private static Map configMap;

    static
    {
        SYSCONFIG = "sysconfig.properties";
        lOG4J = "log4j.properties";
        log = Logger.getLogger(com/comName/common/cache/config/ConfigFileTool);
        configMap = new HashMap();
        try
        {
            PropertiesConfiguration sysconfig = new PropertiesConfiguration(SYSCONFIG);
            configMap.put(SYSCONFIG, sysconfig);
            log.info((new StringBuilder("\u52A0\u8F7D\u7F13\u5B58\u914D\u7F6E\u6587\u4EF6=")).append(sysconfig).toString());
            PropertiesConfiguration log4jconfig = new PropertiesConfiguration(lOG4J);
        }
        catch(ConfigurationException ee)
        {
            log.info("\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6\u9519\u8BEF", ee);
            ee.printStackTrace();
        }
    }
}

// Messages from Jad:
// The class file version is 50.0 (only 45.3, 46.0 and 47.0 are supported)
//


// Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) radix(10) lradix(10)
// Source File Name:   CacheImp.java

package com.comName.common.cache.xmemcache;

import com.comName.common.cache.Cache;
import com.comName.common.cache.CacheManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
import net.rubyeye.xmemcached.MemcachedClient;
import org.apache.log4j.Logger;

public class CacheImp
    implements Cache
{

    public CacheImp(MemcachedClient memcachedClient)
    {
        this.memcachedClient = null;
        this.memcachedClient = memcachedClient;
    }

    public boolean add(String key, Object value)
    {
        boolean addResult = memcachedClient.add(key, CacheManager.getExp().intValue(), value, CacheManager.getSetTimeOut().longValue());
        return addResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u65B0\u589E\u7F13\u5B58\u5931\u8D25\uFF01ex=")).append(ex).toString());
        return false;
    }

    public void addServer(String server, int port, int weight)
    {
        try
        {
            memcachedClient.addServer(server, port, weight);
        }
        catch(IOException e)
        {
            log.info((new StringBuilder("\u589E\u52A0\u7F13\u5B58\u670D\u52A1\u5668\u5931\u8D25\uFF01ex=")).append(e).toString());
            e.printStackTrace();
        }
    }

    public boolean append(String key, Object value)
    {
        boolean appendResult = memcachedClient.append(key, value, CacheManager.getSetTimeOut().longValue());
        return appendResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u8FFD\u52A0\u7F13\u5B58\u5931\u8D25\uFF01ex=")).append(ex).toString());
        return false;
    }

    public boolean delete(String key)
    {
        boolean deleteResult = memcachedClient.delete(key, CacheManager.getSetTimeOut().longValue());
        return deleteResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u5220\u9664\u7F13\u5B58\u5931\u8D25\uFF01ex=")).append(ex).toString());
        return false;
    }

    public void flushAll()
    {
        try
        {
            memcachedClient.flushAll();
        }
        catch(Exception e)
        {
            log.info((new StringBuilder("\u589E\u52A0\u7F13\u5B58\u670D\u52A1\u5668\u5931\u8D25\uFF01ex=")).append(e).toString());
            e.printStackTrace();
        }
    }

    public void flushAll(InetSocketAddress address)
    {
        try
        {
            memcachedClient.flushAll(address);
        }
        catch(Exception e)
        {
            log.info((new StringBuilder("\u5237\u65B0\u6307\u5B9A\u7F13\u5B58\u670D\u52A1\u5668\u5931\u8D25\uFF01ex=")).append(e).toString());
            e.printStackTrace();
        }
    }

    public void shutdown()
        throws IOException
    {
        try
        {
            memcachedClient.shutdown();
        }
        catch(Exception e)
        {
            log.info((new StringBuilder("\u5173\u95ED\u7F13\u5B58\u670D\u52A1\u5668\u5931\u8D25\uFF01ex=")).append(e).toString());
            e.printStackTrace();
        }
    }

    public boolean isShutdown()
    {
        boolean ifShudownResult = memcachedClient.isShutdown();
        return ifShudownResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u65AD\u7F13\u5B58\u670D\u52A1\u5668\u662F\u5426\u5173\u95ED\u5931\u8D25\uFF01ex=")).append(ex).toString());
        return false;
    }

    public Map stats(InetSocketAddress address)
    {
        Map getResult = memcachedClient.stats(address);
        return getResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u7EDF\u8BA1\u7F13\u5B58\u670D\u52A1\u5668\u72B6\u6001\uFF01ex=")).append(ex).toString());
        ex.printStackTrace();
        return null;
    }

    public void removeServer(String hostList)
    {
        try
        {
            memcachedClient.removeServer(hostList);
        }
        catch(Exception ex)
        {
            log.info((new StringBuilder("\u5220\u9664\u7F13\u5B58\u5931\u8D25\uFF01ex=")).append(ex).toString());
        }
    }

    public boolean replace(String key, Object value)
    {
        boolean replaceResult = memcachedClient.replace(key, CacheManager.getExp().intValue(), CacheManager.getSetTimeOut());
        return replaceResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u66FF\u6362\u7F13\u5B58\u5931\u8D25\uFF01ex=")).append(ex).toString());
        return false;
    }

    public boolean set(String key, Object value)
    {
        boolean result = memcachedClient.set(key, CacheManager.getExp().intValue(), value, CacheManager.getSetTimeOut().longValue());
        return result;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u653E\u5165\u7F13\u5B58\u5931\u8D25xxx-key:")).append(key).append(",value=").append(value.toString()).append(" ex=").append(ex).toString());
        ex.printStackTrace();
        return false;
    }

    public Object get(String key)
    {
        Object getResult = memcachedClient.get(key, CacheManager.getGetTimeOut().longValue());
        return getResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("xxx\u8BFB\u53D6\u7F13\u5B58\u5931\u8D25-key:")).append(key).append(" ex=").append(ex).toString());
        ex.printStackTrace();
        return null;
    }

    public Map getStats()
    {
        Map getResult = memcachedClient.getStats();
        return getResult;
        Exception ex;
        ex;
        log.info((new StringBuilder("\u83B7\u53D6\u670D\u52A1\u5668\u72B6\u6001\u5931\u8D25\uFF01ex=")).append(ex).toString());
        ex.printStackTrace();
        return null;
    }

    private MemcachedClient memcachedClient;
    private static Logger log = Logger.getLogger(com/comName/common/cache/CacheManager);

}

// Messages from Jad:
// The class file version is 50.0 (only 45.3, 46.0 and 47.0 are supported)
// Couldn't fully decompile method add
// Couldn't resolve all exception handlers in method add
// Couldn't fully decompile method append
// Couldn't resolve all exception handlers in method append
// Couldn't fully decompile method delete
// Couldn't resolve all exception handlers in method delete
// Couldn't fully decompile method isShutdown
// Couldn't resolve all exception handlers in method isShutdown
// Couldn't fully decompile method stats
// Couldn't resolve all exception handlers in method stats
// Couldn't fully decompile method replace
// Couldn't resolve all exception handlers in method replace
// Couldn't fully decompile method set
// Couldn't resolve all exception handlers in method set
// Couldn't fully decompile method get
// Couldn't resolve all exception handlers in method get
// Couldn't fully decompile method getStats
// Couldn't resolve all exception handlers in method getStats
//


log4j.properties
log4j.rootLogger=INFO,stdout,logfile

log4j.logger.com.comName=INFO
#log4j.logger.org.springframework.jdbc=DEBUG
#log4j.logger.com.ibatis=DEBUG
log4j.logger.org.apache.activemq.transport=FATAL
log4j.logger.org.apache.commons=ERROR
log4j.logger.com.comName.backupmode=ERROR
log4j.logger.org.apache.velocity=ERROR
#stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%p-%t]-[%C %M %L]-%m%n

#ibatis
#log4j.logger.com.ibatis=DEBUG
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
#log4j.logger.java.sql.Connection=DEBUG
#log4j.logger.java.sql.Statement=DEBUG
#log4j.logger.java.sql.PreparedStatement=DEBUG
#log4j.logger.java.sql.ResultSet=DEBUG

#logfile
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${jboss.server.log.dir}/memcached.log
log4j.appender.logfile.MaxFileSize=51200KB
log4j.appender.logfile.MaxBackupIndex=10
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%t-%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%p]-[%C %M %L]-%m%n


sysconfig.properties
#######memcached###########

memcacheServers=172.21.13.57:11211\,172.21.13.58:11213
#cacheServers=172.21.13.57:11211\,172.21.13.58:11211 172.21.13.57:11212\,172.21.13.58:11212
memcacheWeight=1
memcacheConnPoolSize=30
memcacheExp=0
memcacheOpTimeout=3000
memcacheSetTimeOut=2000
memcacheGetTimeOut=2000
memcacheFailureMode=Y



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值