Memcached 客户端使用
Memcached? 客戶(hù)端使用
網(wǎng)上摘抄,以備后用
package com.test.memcache;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/**
?* 利用開(kāi)源項(xiàng)目danga.MemCached管理緩存,實(shí)現(xiàn)分布式緩存支持。
?* 在調(diào)試時(shí)使用了memcached-1.2.6-win32-binary安裝,在部署時(shí)需要build linux版本部署。 服務(wù)器默認(rèn)端口是11211
?*/
public class MemCacheManager {
// 創(chuàng)建全局的唯一實(shí)例
protected static MemCachedClient mcc = null;
protected static MemCacheManager memCacheManager = null;
/**
* 保護(hù)型構(gòu)造方法!
*?
*/
protected MemCacheManager() {
}
/**
* 獲取唯一實(shí)例.
*?
* @return
*/
public static MemCacheManager getInstance() {
// 設(shè)置與緩存服務(wù)器的連接池
if (memCacheManager == null) {
// 獲取socke連接池的實(shí)例對(duì)象
SockIOPool pool = SockIOPool.getInstance();
String server ="127.0.0.1";
String port ="11211";
String[] servers = { server+":"+port};
// 設(shè)置服務(wù)器信息
pool.setServers(servers);
// 與服務(wù)器列表中對(duì)應(yīng)的各服務(wù)器的權(quán)重,權(quán)重高的負(fù)載大
Integer[] weights = { 3 };
pool.setWeights(weights);
// 設(shè)置初始連接數(shù)、最小和最大連接數(shù)以及最大處理時(shí)間
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000 * 60 * 60 * 6);
// 設(shè)置主線(xiàn)程的睡眠時(shí)間
pool.setMaintSleep(30);
// 設(shè)置TCP的參數(shù),連接超時(shí)等
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
// 初始化連接池
pool.initialize();
// 壓縮設(shè)置,超過(guò)指定大小(單位為K)的數(shù)據(jù)都會(huì)被壓縮
MemCachedClient mcc = new MemCachedClient();
mcc.setCompressEnable(true);
mcc.setCompressThreshold(64 * 1024);
memCacheManager = new MemCacheManager();
memCacheManager.mcc = mcc;
}
return memCacheManager;
}
/**
* 添加一個(gè)指定的值到緩存中.
*?
* @param key
* @param value
* @return
*/
public boolean put(String key, Object value) {
return mcc.add(key, value);
}
public boolean put(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);
}
/**
* 根據(jù)指定的關(guān)鍵字獲取對(duì)象.
*?
* @param key
* @return
*/
public Object get(String key) {
Object rv= ?mcc.get(key);
return rv;
}
}
? ? ? 本文轉(zhuǎn)自yjflinchong 51CTO博客,原文鏈接:http://blog.51cto.com/yjflinchong/1164957,如需轉(zhuǎn)載請(qǐng)自行聯(lián)系原作者
總結(jié)
以上是生活随笔為你收集整理的Memcached 客户端使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 性能测试工具Curl-Loader
- 下一篇: 第3章 IP寻址