import java.sql.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class MemCached {
//创建全局唯1的实例
protected static MemCachedClient mcc=new MemCachedClient();
protected static MemCached memCached=new MemCached();
//设置与缓存
服务器的连接池
static{
//
服务器列表和其权重
String[] servers={"127.0.0.1:11211"};
Integer[] weights={3};
//获得socket连接池的实例对象
SockIOPool pool=SockIOPool.getInstance();
//设置
服务器信息
pool.setServers(servers);
pool.setWeights(weights);
//设置初始连接数、最小和最大连接数和最大处理时间
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000*60*60*6);
//设置主线程的睡眠时间
pool.setMaintSleep(30);
//设置TCP的参数、连接超时等
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
//初始化连接池
pool.initialize();
// 紧缩设置,超过指定大小(单位为K)的数据都会被紧缩
mcc.setCompressEnable(true);
mcc.setCompressThreshold(64 * 1024);
}
/**
* 保护型构造,不允许实例化
*/
protected MemCached(){}
/**
* 获得唯1实例
*/
public static MemCached getInstance(){
return memCached;
}
/**
* 添加1个指定的值dao缓存中
*/
public boolean add(String key,Object value){
return mcc.add(key,value);
}
public boolean add(String key,Object value,Date expiry){
return mcc.add(key,value,expiry);
}
public boolean replace(String key,Object value){
return mcc.replace(key,value);
}
public boolean replace(String key,Object value,Date expiry){
return mcc.replace(key, value,expiry);
}
/**
* 根据指定的关键字获得对象
*/
public Object get(String key){
return mcc.get(key);
}
public static void main(String[] args) {
MemCached cached=MemCached.getInstance();
//cached.add("hello",1223);
System.out.println("get Value:"+cached.get("hello"));
}
}
需要的jar包:
java_memcached-release_1.6.jar
在运行之前要启动Memcached服务,以下: