import java.io.Serializable;
import java.text.DateFormat;
import java.util.Date;
import java.util.Map; import com.danga.MemCached.MemCachedClient;
import com.pt.util.memcached.MemcachedTool; public class testMemcached { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MemCachedClient mc = MemcachedTool.getInstance();
//(1000 * 129是本地时间和服务器端时间的差值)
Date failDate = new Date(System.currentTimeMillis() - 1000 * 129 + 10000);
System.out.println(failDate);
mc.set("c", "230",failDate); //如果有相同的key值,则替换掉原先的值 失效时间(以服务器的时间为准)
Boolean add = mc.add("b", "110"); //如果存在同样key值,则返回false
String str = (String)mc.get("c");
String[] keys = {"a","b"};
Map strs = mc.getMulti(keys); //获取多个值 返回结果是一个数组
System.out.println("get value from memcached: " + str);
mc.delete("c"); //删除key System.out.println("test add method: " + add);
System.out.println("get params: " + strs); //写入对象
user men = new user();
men.setId(1907);
men.setName("潘腾");
boolean setObj = mc.set("user", men);
user getMen = (user)mc.get("user");
System.out.println(getMen);
} } class user implements Serializable{
String name;
int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "name: " + name + " id: " + id;
} }

testMain

 package com.pt.util.memcached;

 import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool; public class MemcachedTool {
private static MemCachedClient memcacheClient = null; private MemcachedTool(){ } public static MemCachedClient getInstance(){
if(memcacheClient == null){
memcacheClient = new MemCachedClient();
memcacheClient.setDefaultEncoding("UTF-8"); //写入缓存的编码格式 }
return memcacheClient;
} static{
String[] serversArray = {"192.168.65.221:13220"};
Integer[] weight = {1};
SockIOPool connPool = SockIOPool.getInstance();
connPool.setServers(serversArray); //设置memcached服务器
connPool.setWeights(weight); //设置各个服务器存储权重
connPool.setMinConn(3); //设置连接池的最小连接数目
connPool.setInitConn(3); //初始化可用连接数目
connPool.setMaxIdle(10000); //可用连接池最长等待时间
connPool.setSocketTO(10000); //读取等待超时值
connPool.setSocketConnectTO(10000); //连接等待超时值
//心跳检测,设置为true时,每次通信都会先检测连接是否可用 增加IO和网络开销,一般设置为false 默认是false
connPool.setAliveCheck(false);
/**
* alg=0 使用String.hashCode()获得hash code,该方法依赖JDK,可能和其他客户端不兼容,建议不使用
* alg=1 使用original 兼容hash算法,兼容其他客户端
* alg=2 使用CRC32兼容hash算法,兼容其他客户端,性能优于original算法
* alg=3 使用MD5 hash算法
* 采用前三种hash算法的时候,查找cache服务器使用余数方法。采用最后一种hash算法查找cache服务时使用consistent方法。
**/
connPool.setHashingAlg(3);
//设置服务器宕机或连接由中断变为恢复后,该连接继续可用
connPool.setFailback(true);
//启动pool
connPool.initialize();
}
}

MemcacheTool

需要引入:java-memcached-release_2.5.2.jar包

05-11 04:47