1:下载jar包
2:memcached.properties
#memcacheServer = 192.168.28.205:11211
3:MemcachedUtil.java
package com.bdcDataException.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/**
* MemCache缓存工具类
*
* @author kwq
* @since 2009-11-27
*
*/
public class MemCacheUtil {
private static Log log = LogFactory.getLog(MemCacheUtil.class);
private static MemCachedClient cache = new MemCachedClient();
static {
init();
}
public static String getServerStr() {
Properties props = new Properties();
try {
props.load(MemCacheUtil.class
.getResourceAsStream("/memcached.properties"));
return (String) props.get("memcacheServer");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "192.168.28.205:11211";
}
private static void init() {
String serverstr = getServerStr();
log.info("Servers:" + serverstr);
if (serverstr == null || "".equals(serverstr.trim())) {
ResourceBundle rb = ResourceBundle.getBundle("memcached");
// 缓存服务器地址
serverstr = rb.getString("memcacheServer");
rb = null;
}
log.debug("memcached:" + serverstr);
String[] serverArray = serverstr.split(",");
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(serverArray);
pool.setFailover(true);
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(255);
pool.setMaxIdle(10 * 60 * 1000);
// 设置主线程的睡眠时间
pool.setMaintSleep(30);
// TCP的规则就是在发送一个包之前,本地机器会等待远程主机
// 对上一次发送的包的确认信息到来;这个方法就可以关闭套接字的缓存,
// 以至这个包准备好了就发;
pool.setNagle(false);
// 连接建立后对超时的控制
pool.setSocketTO(3000);
// 连接建立时对超时的控制
pool.setSocketConnectTO(0);
// initialize the connection pool
// 初始化一些值并与MemcachedServer段建立连接
pool.initialize();
// lets set some compression on for the client
// compress anything larger than 64k
cache.setCompressEnable(true);
cache.setCompressThreshold(64 * 1024);
}
/**
* 清除缓存
*
* @return
*/
public static void removeAll() {
try {
cache.flushAll();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void remove(String key) {
try {
cache.delete(key);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object get(String key) {
try {
return cache.get(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Map<String, Object> getMulti(String[] keys) {
try {
return cache.getMulti(keys);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* @param key
* @param value
*/
public static void add(String key, Object value) {
try {
cache.set(key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param key
* @param value
* @param expiry
*/
public static void put(String key, Object value, Date expiry) {
try {
cache.set(key, value, expiry);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
MemCacheUtil.add("kwq1", "kwq1,kwq");
MemCacheUtil.add("kwq2", "kwq2,kwq");
MemCacheUtil.add("kwq3", "kwq3,kwq");
Map<String, Object> map = MemCacheUtil.getMulti(new String[] { "kwq1",
"kwq2", "kwq3" });
System.out.println(map);
// Object obj = FlightsCacheAPI.getFlights("PEK", "PVG", "2011-06-03");
// System.out.println(obj);
}
}
4:创建自己的mencached实例使用
/**
* @Title: ClassResultCached.java
* @Package com.bdcDataException.utils
* @createAuthor liuyunbin
* @createdate 2011-11-1 下午3:17:12
*/
package com.bdcDataException.utils;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.besttone.bdc.api.CHRequestKeyword;
import com.besttone.bdc.api.CHRequestParam;
import com.besttone.bdc.api.ClassifyReslut;
/**
* @Title: ClassResultCached.java
* @Package com.bdcDataException.utils
* @ClassName: ClassResultCached
* @Description: TODO(用一句话描述该文件做什么)
* @author liuyunbin
* @date 2011-11-1 下午3:17:12
* @version V1.0
*
*/
public class ClassResultCached {
// public static Map<String, List<ClassifyReslut>> mapList = new
// HashMap<String, List<ClassifyReslut>>();
public static List<ClassifyReslut> get(CHRequestParam parma) {
String key = toClassifyKey(parma);
// if(key!=null)
// return mapList.get(key);
if (key != null)
return (List<ClassifyReslut>) MemCacheUtil.get(key);
return null;
}
/**
* @Title: set
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param parma
* @param listClassifyReslut
*/
public static void set(CHRequestParam parma,
List<ClassifyReslut> listClassifyReslut) {
if (listClassifyReslut == null || listClassifyReslut.size() == 0)
return;
if (parma.getKeyword() == null)
return;
if (parma.getKeyword().getC2() != null
&& !parma.getKeyword().getC2().equals(""))
return;
MemCacheUtil
.put(toClassifyKey(parma), listClassifyReslut, getTimeout());
// mapList.put(toClassifyKey(parma), listClassifyReslut);
}
/**
* @Title: toClassifyKey
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param parma
* @return
*/
private static String toClassifyKey(CHRequestParam parma) {
if (parma == null || parma.getKeyword() == null)
return null;
CHRequestKeyword rkw = parma.getKeyword();
StringBuffer key = new StringBuffer();
key.append("region: " + parma.getRegion() + ",");
key.append("name: " + rkw.getName() + ",");
key.append("phone: " + rkw.getPhone() + ",");
key.append("address: " + rkw.getAddress() + ",");
key.append("industry: " + rkw.getIndustry() + ",");
key.append("keyword: " + rkw.getKeyword() + ",");
key.append("lable: " + rkw.getLable() + ",");
key.append("isDC: " + rkw.getIsDC() + ",");
key.append("isDF: " + rkw.getIsDF() + ",");
key.append("isYHQ: " + rkw.getIsYHQ() + ",");
key.append("isJM: " + rkw.getIsJM() + ",");
key.append("isDP: " + rkw.getIsDP() + ",");
if (rkw.getC1() != null && !rkw.getC1().equals("")) {
key.append("c1: " + rkw.getC1() + ",");
}
return MD5Builder.getMD5(key.toString());
}
public static Date getTimeout() {
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
return cal.getTime();
}
}
5:MD5加密 用于key的加密
package com.bdcDataException.utils;
import java.security.MessageDigest;
import org.apache.log4j.Logger;
public class MD5Builder {
static Logger logger = Logger.getLogger(MD5Builder.class);
// 用来将字节转换成 16 进制表示的字符
static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 对一段String生成MD5加密信息
*
* @param message
* 要加密的String
* @return 生成的MD5信息
*/
public static String getMD5(String message) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// logger.info("MD5摘要长度:" + md.getDigestLength());
byte[] b = md.digest(message.getBytes("UTF-8"));
return byteToHexString(b);
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
return null;
}
}
/**
* 把byte[]数组转换成十六进制字符串表示形式
*
* @param tmp
* 要转换的byte[]
* @return 十六进制字符串表示形式
*/
private static String byteToHexString(byte[] tmp) {
String s;
// 用字节表示就是 16 个字节
char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
s = new String(str); // 换后的结果转换为字符串
return s;
}
}