MemcachedUtil 工具类

1 篇文章 0 订阅
1 篇文章 0 订阅

/**
*
*/
package org.lang2hong.utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author jianping.gao
*
*/
public class MemcachedUtil {
/**
* slf4j logback
*/
private final static Logger logger = LoggerFactory
.getLogger(MemcachedUtil.class);

public static MemcachedClient memcachedClient;

/*
 * 本地ip 支持多个测试人员同时使用同一个缓存
 */
private static String ip;

/*
 * 缓存时间
 */
private static int catchTime = 5 * 60 * 60;

/*
 * 支持多个测试人员同时使用同一个缓存
 */
static {
    InetAddress addr;
    try {
        addr = InetAddress.getLocalHost();
        ip = addr.getHostAddress().toString();// 获得本机IP
    } catch (UnknownHostException e) {
        logger.error("Unknown host exception ", e);
        ip = "127.0.0.1";
    }
}

/*
 * memcachedClient Instance
 */
public static void memcachedClientInstance(Properties p) {
    MemcachedClientBuilder builder = null;
    try {
        builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(p
                .getProperty("memcached.server1.host")
                + ":"
                + p.getProperty("memcached.server1.port")
                + " "
                + p.getProperty("memcached.server2.host")
                + ":"
                + p.getProperty("memcached.server2.port")), new int[] { 4,
                3 });
        // 宕机报警
        builder.setFailureMode(true);
        memcachedClient = builder.build();
    } catch (IOException e) {
        logger.error("memcachedClient Exception : {}", e);
        try {
            memcachedClient = builder.build();
        } catch (IOException e1) {
            logger.error("reinit memcachedClient Exception : {}", e);
        }
    }
}

/**
 *
 * 再次尝试连接服务器
 *
 */
private static void reConnectMemcachedServer() {
    int i = 0;
    memcachedClient = null;
    Properties p = PropertiesBundle
            .loadProperties(PropertiesBundle.MEMCACHED);
    while (i < 3) {
        memcachedClientInstance(p);
        if (memcachedClient != null) {
            logger.info("try connect Memcached Server is success again ");
            break;
        }
    }
    if (i >= 3) {
        logger.info("try connect Memcached Server is fail !");
    }
}

/**
 * 从缓存中获取对应value
 *
 * true:被测试系统 false:本系统
 */
public static Object getValue(String key, boolean isAuto) {
    Object val = null;
    try {
        if (memcachedClient == null) {
            reConnectMemcachedServer();
        }
        if (isAuto) {
            val = memcachedClient.get(key + ip);
            logger.debug("memcached : key=[{}]    val=[{}]", key, val);
        } else {
            val = memcachedClient.get(key);
            logger.debug("memcached : key=[{}]    val=[{}]", key + ip, val);
        }
    } catch (TimeoutException e) {
        logger.debug("Memcache TimeoutException  : {}", e);
        return getValue(key, isAuto, null);
    } catch (InterruptedException e) {
        logger.debug("Memcache InterruptedException  : {}", e);
        return getValue(key, isAuto, null);
    } catch (MemcachedException e) {
        logger.debug("Memcache MemcachedException  : {}", e);
        return getValue(key, isAuto, null);
    }
    return val;
}

/**
 * 如果第一次获取缓存异常,则再次获取
 *
 * @param key
 * @param isAuto
 * @return
 * @throws IOException
 */
private static Object getValue(String key, boolean isAuto, String re) {
    reConnectMemcachedServer();
    return getValue(key, isAuto);
}

/**
 * 删除缓存中对应key和value
 *
 * @param key
 * @return
 */
public static void delValue(String key) {
    try {
        if (memcachedClient == null) {
            reConnectMemcachedServer();
        }
        memcachedClient.delete(key + ip);
        logger.info("delete memcached : key=[{}]", key + ip);
        return;
    } catch (MemcachedException e) {
        logger.debug("Memcache MemcachedException  : {}", e);
        delValue(key, null);
        return;
    } catch (TimeoutException e) {
        logger.debug("Memcache TimeoutException  : {}", e);
        delValue(key, null);
        return;
    } catch (InterruptedException e) {
        logger.debug("Memcache MemcachedException  : {}", e);
        delValue(key, null);
        return;
    }
}

/**
 * 删除缓存中对应key和value
 *
 * @param key
 * @param re
 * @return
 */
public static void delValue(String key, String re) {
    reConnectMemcachedServer();
    delValue(key);
}


/**
 * 将数据放入缓存
 *
 * @param key
 * @return
 */
public static void setValue(
        String key, Object value) {
    try {
        memcachedClient.set(key + ip, catchTime, value);
        logger.info("set memcached : key=[{}]    val=[{}]", key + ip, value);
    } catch (MemcachedException e) {
        logger.info("Memcache MemcachedException  : {}", e);
        setValue(key, value, null);
        return;
    } catch (TimeoutException e) {
        setValue(key, value, null);
        return;
    } catch (InterruptedException e) {
        setValue(key, value, null);
        return;
    }
}

/**
 * 再次尝试将数据放入缓存
 *
 * @param key
 * @param value
 * @param re
 */
public static void setValue(String key, Object value, String re) {
    reConnectMemcachedServer();
    setValue(key, value);
}

/**
 * memcached shut down
 */
public static void shutDown() {
    try {
        memcachedClient.shutdown();
    } catch (IOException e) {
        logger.info("Memcache IOException  : {}", e);
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package teacherclub.util; import java.io.File; import java.io.InputStream; import java.util.Date; import java.util.Properties; import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool; /** * @author Chergen * */ public class MCCUtil { /** * @param args */ protected static MemCachedClient mcc = new MemCachedClient(); /**�Ƿ���� MCC*/ private static boolean IS_DISABLED = false; /**Ĭ��ʧЧʱ��*/ private static long DEF_EXPIRE = 10000; /**���� �Ƿ���� MCC<br>true:���ã�false:����*/ public static void setDisable(boolean isDisable){ IS_DISABLED = isDisable; if(!IS_DISABLED) init(); } /**���� Ĭ��ʧЧʱ��*/ public static void setDefExpire(long expire){ DEF_EXPIRE = expire; } static { init(); } private static void init(){ Properties props = new Properties(); try{ String path = WebUtil.getWebinfPath()+File.separatorChar+"properties"+File.separatorChar+"mcc.properties"; File file = new File(path); InputStream is = new java.io.FileInputStream(file); props.load(is); is.close(); System.out.println("Successfully initialize MCC!"); }catch(Exception e){ IS_DISABLED = true; System.out.println("Failed to initialize MCC!\nPleanse check out the mcc.properties."); e.printStackTrace(); return ; } String[] servers = props.getProperty("mcc.servers", "localhost:11211").split(",");//{ "mcc.host:11211" }; String[] weightsStr = props.getProperty("mcc.weights", "3").split(","); Integer[] weights = new Integer[weightsStr.length];//{ 3 }; for (int i = 0; i < weightsStr.length; i++) { try{ weights[i] = Integer.parseInt(weightsStr[i]); }catch(Exception e){weights[i] = 3;} } // ����һ��ʵ�����SockIOPool SockIOPool pool = SockIOPool.getInstance(); // set the servers and the weights // ����Memcached Server pool.setServers(servers); pool.setWeights(weights); // set some basic pool settings // 5 initial, 5 min, and 250 max conns // and set the max idle time for a conn // to 6 hours pool.setInitConn(5); pool.setMinConn(5); pool.setMaxConn(250); pool.setMaxIdle(1000 * 60 * 60 * 12); // set the sleep for the maint thread // it will wake up every x seconds and // maintain the pool size pool.setMaintSleep(30); // Tcp�Ĺ�������ڷ���һ���֮ǰ�����ػ����ȴ�Զ����� // ����һ�η��͵İ��ȷ����Ϣ��4�������Ϳ��Թر��׽��ֵĻ��棬 // ��������׼�����˾ͷ��� pool.setNagle(false); // l�ӽ�b��Գ�ʱ�Ŀ��� pool.setSocketTO(3000); // l�ӽ�bʱ�Գ�ʱ�Ŀ��� pool.setSocketConnectTO(0); // initialize the connection pool // ��ʼ��һЩֵ����MemcachedServer�ν�bl�� pool.initialize(); // lets set some compression on for the client // compress anything larger than 64k mcc.setCompressEnable(true); mcc.setCompressThreshold(64 * 1024); } /**�������*/ public static void inputData(String key, Object Data){ inputData(key, Data, DEF_EXPIRE); } /**�������*/ public static void inputData(String key, Object Data, long expire){ if(!IS_DISABLED) mcc.set(key, Data, new Date(expire)); } /**ȡ�����*/ public static Object outputData(String key){ if(IS_DISABLED) return null; return mcc.get(key); } private static void bulidCache() { // set(key,value,Date) ,Date��һ�����ʱ�䣬�������������ʱ����Ч�Ļ������ﴫ�ݵ�new Date(long // date) �в���date����Ҫ�Ǹ���ڻ����1000��ֵ�� // ��Ϊjava client��ʵ��Դ����������ʵ�ֵ� expiry.getTime() / 1000 ��Ҳ����˵����� // С��1000��ֵ������1000�Ժ���0�����2����� mcc.set("test", "This is a test String", new Date(10000)); // ʮ������ } private static void output() { // ��cache��ȡֵ String value = (String) mcc.get("test"); System.out.println(value); } public static void main(String[] args) { bulidCache(); output(); } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值