Memcache 程式設計(安裝及配置)
阿新 • • 發佈:2019-01-05
安裝及配置
- 安裝 Homebrew:https://brew.sh/index_zh-cn.html
- 安裝 Memcache
- brew search memcache
- 安裝伺服器:brew install memcached
- 啟動 :/usr/local/Cellar/memcached/1.5.12/bin/memcached -d -m 1024 -l 127.0.0.1 -p 11211
-
- 啟動Memcache 常用引數
- -p 設定TCP埠號(預設設定為: 11211)
- -U UDP監聽埠(預設: 11211, 0 時關閉)
- -l 繫結地址(預設:所有都允許,無論內外網或者本機更換IP,有安全隱患,若設定為127.0.0.1就只能本機訪問)
- -c max simultaneous connections (default: 1024)
- -d 以daemon方式執行
- -u 繫結使用指定用於執行程序
- -m 允許最大記憶體用量,單位M (預設: 64 MB)
- -P 將PID寫入檔案,這樣可以使得後邊進行快速程序終止, 需要與-d 一起使用
-
- 連線:
-
- brew install telnet
- telnet 127.0.0.1 11211
特點
- Memory,記憶體儲存。
- 集中式 Cache,多個 Memcache 作為一個虛擬的 Cluster。
- 分散式擴充套件,將一臺伺服器上的多個 Memcache 服務端部署到多個伺服器上。
- Socket 通訊,儘量儲存較小內容,且採用字串傳輸,省去序列化的操作。
- 記憶體分配機制,支援的最大儲存物件為 1MB。
- Cache 機制,沒有同步、訊息分發或兩階段提交,Key 命中則返回,不命中則需要到資料來源中去讀取,容許失效時間。
使用場景
- 小物件快取:使用者 Token,許可權,session,資源資訊等。
- 小的靜態資源的快取,如網站的首頁。
- 資料庫 SQL 結果集的快取,對於資料庫的負載有很大的減緩作用。
使用示例
建立一個 MemCachedClient 物件的同時建立一個同名的 SockIOPool 物件。
Memcache 工具類封裝
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import java.util.Arrays;
/**
* 安裝 Homebrew:https://brew.sh/index_zh-cn.html
* 安裝 Memcache
* brew search memcache
* 安裝伺服器:brew install memcached
* 啟動 :/usr/local/Cellar/memcached/1.5.12/bin/memcached -d -m 1024 -l 127.0.0.1 -p 11211
* <p>
* 啟動Memcache 常用引數
* -p 設定TCP埠號(預設設定為: 11211)
* -U UDP監聽埠(預設: 11211, 0 時關閉)
* -l 繫結地址(預設:所有都允許,無論內外網或者本機更換IP,有安全隱患,若設定為127.0.0.1就只能本機訪問)
* -c max simultaneous connections (default: 1024)
* -d 以daemon方式執行
* -u 繫結使用指定用於執行程序
* -m 允許最大記憶體用量,單位M (預設: 64 MB)
* -P 將PID寫入檔案,這樣可以使得後邊進行快速程序終止, 需要與-d 一起使用
* <p>
* 連線:
* <p>
* brew install telnet
* telnet 127.0.0.1 11211
*
* jar
*/
public class MemcachedCRUD {
public static String poolName = "DBPool";
protected static MemCachedClient memCachedClient;
protected static MemcachedCRUD memcachedCRUD = new MemcachedCRUD();
public static SockIOPool sockIoPool;
static {
sockIoPool = init(poolName, "cacheServer");
memCachedClient = new MemCachedClient(poolName);
// if true, then store all primitives as their string value.
memCachedClient.setPrimitiveAsString(true);
}
public static SockIOPool init(String poolName, String confKey) {
// 快取伺服器
String server[] = {"127.0.0.1:11211"};
// 建立一個連線池
SockIOPool pool = SockIOPool.getInstance(poolName);
System.out.println("連線池" + poolName + "快取配置" + Arrays.toString(server));
pool.setServers(server);// 快取伺服器
pool.setInitConn(50); // 初始化連結數
pool.setMinConn(50); // 最小連結數
pool.setMaxConn(500); // 最大連線數
pool.setMaxIdle(1000 * 60 * 60);// 最大處理時間
pool.setMaintSleep(3000);// 設定主執行緒睡眠時,每3秒甦醒一次,維持連線池大小
pool.setNagle(false);// 關閉套接字快取
pool.setSocketTO(3000);// 連結建立後超時時間
pool.setSocketConnectTO(0);// 連結建立時的超時時間
pool.initialize();
return pool;
}
public static void destroy() {
sockIoPool.shutDown();
}
MemcachedCRUD() {
}
public static MemcachedCRUD getInstance() {
return memcachedCRUD;
}
private static final long INTERVAL = 100;
public boolean add(String key, Object o) {
return memCachedClient.add(key, o);
}
public boolean update(String key, Object o) {
return memCachedClient.replace(key, o);
}
public boolean saveObject(String key, Object msg) {
boolean o = memCachedClient.keyExists(key);
if (o) {// 存在替換掉
return memCachedClient.replace(key, msg);
} else {
return memCachedClient.add(key, msg);
}
}
public boolean keyExist(String key) {
return memCachedClient.keyExists(key);
}
/**
* delete
*
* @param key
*/
public boolean deleteObject(String key) {
return memCachedClient.delete(key);
}
public Object getObject(String key) {
Object obj = memCachedClient.get(key);
return obj;
}
public static MemCachedClient getMemCachedClient() {
return memCachedClient;
}
}
Memcache 工具類呼叫
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MemcacheClientDemo {
public static void main(String[] args) {
MemcacheClientDemo demo = new MemcacheClientDemo();
demo.run();
}
public void run() {
/** memcache add **/
MemcachedCRUD memcache = MemcachedCRUD.getInstance();
System.out.println("===========memcache add==============");
memcache.add("testKey1", 1);
memcache.add("testKey2", "test value");
List<String> list = new ArrayList<String>();
list.add("string1");
list.add("string2");
list.add("string3");
list.add("string4");
memcache.add("testKey3", list);
Map<Long, List<String>> map = new HashMap<Long, List<String>>();
map.put(1l, list);
map.put(2l, null);
map.put(3l, list);
memcache.add("testKey4", map);
/** memcache get **/
System.out.println("===========memcache get==============");
int val1 = Integer.parseInt((String) memcache.getObject("testKey1"));
System.out.println("val1:" + val1);
String val2 = (String) memcache.getObject("testKey2");
System.out.println("val2:" + val2);
List<String> val3 = (List<String>) memcache.getObject("testKey3");
System.out.print("val3:");
for (String string : val3) {
System.out.print(string + ",");
}
System.out.println();
Map<Long, List<String>> val4 = (Map<Long, List<String>>) memcache.getObject("testKey4");
System.out.print("val4:");
for (Long key : val4.keySet()) {
System.out.print("key:" + key + ",value:" + val4.get(key));
}
System.out.println();
/** memcache update **/
System.out.println("===========memcache update==============");
memcache.saveObject("testKey2", "val after update");
String updateVal = (String) memcache.getObject("testKey2");
System.out.println("val2 after update:" + updateVal);
/** memcache key Exist **/
System.out.println("===========memcache key Exist==============");
boolean flag = memcache.keyExist("testKey2");
System.out.println("is testKey2 exist:" + flag);
/** memcache delete **/
System.out.println("===========memcache delete==============");
memcache.deleteObject("testKey3");
boolean delFlag = memcache.keyExist("testKey3");
System.out.println("is testKey3 exist after delete:" + delFlag);
}
}