java中一个memcached案例
- package com.wzpmt;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import com.danga.MemCached.MemCachedClient;
- import com.danga.MemCached.SockIOPool;
- 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 < 10000*1000; i++) {
- cache.add("test"+i , "中国");
- }
- long endDate=System.currentTimeMillis();
- long nowDate=(endDate-startDate)/1000;
- System.out.println(nowDate);
- System.out.print( " get value : " + cache.get( "test" ));
- }
- }
下面来一个高度封装的memcached工具类;如下:
package com.hoodong.framework.cache;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.hoodong.framework.util.FrameProperties;
public class MemCached {
private static Map cachePool = new ConcurrentHashMap();
/**
* 取得指定memcached.
* @param cacheName
* @return
*/
public static MemCachedClient getCache(String cacheName) {
if (cacheName == null && "".equals(cacheName.trim())) {
return null;
}
if (cachePool.get(cacheName) == null
|| !(cachePool.containsKey(cacheName))) {
String fileName=cacheName+".xml";
MemCachedClient cacheClient = initMemecached(fileName);
if (cacheClient == null) {
return null;
} else {
cachePool.put(cacheName, cacheClient);
return cacheClient;
}
}
return (MemCachedClient) cachePool.get(cacheName);
}
// 设置与缓存服务器的连接池
private static MemCachedClient initMemecached(String filename) {
String poolName = FrameProperties.getProperties(filename, "poolName");
// 得到一个实例对象SockIOPool
SockIOPool pool = SockIOPool.getInstance(poolName);
//先判断pool是否已经被初始化
if(!pool.isInitialized()){
String serverList = FrameProperties.getProperties(filename, "serverList");
String weightList = FrameProperties.getProperties(filename, "weightList");
String minConn = FrameProperties.getProperties(filename, "minConn");
String initConn = FrameProperties.getProperties(filename, "initConn");
String maxConn = FrameProperties.getProperties(filename, "maxConn");
String maxIdle = FrameProperties.getProperties(filename, "maxIdle");
String maintSleep = FrameProperties.getProperties(filename, "maintSleep");
String socketTO = FrameProperties.getProperties(filename, "socketTO");
String socketConnectTO = FrameProperties.getProperties(filename, "socketConnectTO");
String aliveCheck = FrameProperties.getProperties(filename, "aliveCheck");
String nagle = FrameProperties.getProperties(filename, "nagle");
String failover = FrameProperties.getProperties(filename, "failover");
String failback = FrameProperties.getProperties(filename, "failback");
String[] serversStr = serverList.split(",");
String[] servers = new String[serversStr.length];
for (int i = 0; i < servers.length; i++) {
servers[i] = serversStr[i];
}
String[] weightsStr = weightList.split(",");
Integer[] weights = new Integer[weightsStr.length];
for (int i = 0; i < weights.length; i++) {
weights[i] = new Integer(weightsStr[i]);
}
// 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(Integer.parseInt(initConn));
pool.setMinConn(Integer.parseInt(minConn));
pool.setMaxConn(Integer.parseInt(maxConn));
pool.setMaxIdle(Long.parseLong(maxIdle));
// set the sleep for the maint thread
// it will wake up every x seconds and
// maintain the pool size
pool.setMaintSleep(Long.parseLong(maintSleep));
// Tcp的规则就是在发送一个包之前,本地机器会等待远程主机
// 对上一次发送的包的确认信息到来;这个方法就可以关闭套接字的缓存,
// 以至这个包准备好了就发;
pool.setNagle(Boolean.parseBoolean(nagle));
// 连接建立后对超时的控制
pool.setSocketTO(Integer.parseInt(socketTO));
// 连接建立时对超时的控制
pool.setSocketConnectTO(Integer.parseInt(socketConnectTO));
pool.setAliveCheck(Boolean.parseBoolean(aliveCheck));
pool.setFailover(Boolean.parseBoolean(failover));
pool.setFailback(Boolean.parseBoolean(failback));
pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);
// initialize the connection pool
// 初始化一些值并与MemcachedServer段建立连接
// 初始化连接池
pool.initialize();
}
// 压缩设置,超过指定大小(单位为K)的数据都会被压缩
MemCachedClient mcc = new MemCachedClient(poolName);
String primitiveAsString = FrameProperties.getProperties(filename, "primitiveAsString");
String compressEnable = FrameProperties.getProperties(filename, "compressEnable");
mcc.setCompressEnable(Boolean.parseBoolean(compressEnable));
//mcc.setCompressThreshold(64 * 1024);//默认15k
mcc.setPrimitiveAsString(Boolean.parseBoolean(primitiveAsString));
mcc.setSanitizeKeys(false);
return mcc;
}
/**
* 销毁缓存
*/
protected void finalize() throws Throwable {
cachePool.clear();
cachePool=null;
super.finalize();
}
public static void main(String a[])
{
MemCachedClient m= MemCached.getCache("mclient0");
m.set("a", 1);
m.set("b", 2);
m.set("c", 3);
System.out.println(m.get("a"));
System.out.println(m.get("b"));
System.out.println(m.get("c"));
}
}
转载请指明出处:http://blog.csdn.net/yangkai_hudong
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。