一、MemCachedManager
public class MemCachedManager {
// 创建全局的唯一实例
protected static MemCachedClient mcc = new MemCachedClient();
protected static MemCachedManager memCached = new MemCachedManager();
// 设置与缓存服务器的连接池
static {
// 服务器列表和其权重
String[] servers = { "127.0.0.1:11211" };
Integer[] weights = { 3 };
// 获取socke连接池的实例对象
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 MemCachedManager()
{
}
/**
* 获取唯一实例.
* @return
*/
public static MemCachedManager getInstance()
{
return memCached;
}
/**
* 添加一个指定的值到缓存中.
* @param key
* @param value
* @return
*/
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);
}
/**
* 根据指定的关键字获取对象.
* @param key
* @return
*/
public Object get(String key)
{
return mcc.get(key);
}
public static void main(String[] args)
{
MemCachedManager cache = MemCachedManager.getInstance();
long startDate=System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
cache.add("test"+i , "china");
}
long endDate=System.currentTimeMillis();
long nowDate=(endDate-startDate)/1000;
System.out.println(nowDate);
System.out.print( " get value : " + cache.get( "test"+5 ));
}
}
二、MemCacheInvoke
public class MemCacheInvoke {
protected static MemCachedClient mcc = new MemCachedClient();
static{
// 设置缓存服务器列表,当使用分布式缓存的时,可以指定多个缓存服务器。这里应该设置为多个不同的服务,我这里将两个服务设置为一样的,大家不要向我学习,呵呵。
String[] servers =
{
"10.15.0.215:46697",
"10.15.0.215:46697",
// "server3.mydomain.com:1624"
};
// 设置服务器权重
Integer[] weights = {3, 2};
// 创建一个Socked连接池实例
SockIOPool pool = SockIOPool.getInstance();
// 向连接池设置服务器和权重
pool.setServers(servers);
pool.setWeights(weights);
// set some TCP settings
// disable nagle
// set the read timeout to 3 secs
// and don't set a connect timeout
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
// initialize the connection pool
pool.initialize();
}
public static void main(String[] args) {
mcc.set("foo", "This is a test String");
String bar = mcc.get("foo").toString();
System.out.println(">>> " + bar);
}
}