Memcached 以簡單、高性能、純內存著稱,协议极简。本文整理生產常用命令,並深度對比三大主流 Java 客戶端:Danga (最早/最廣)、SpyMemcached (異步/未來)、XMemcached (NIO/高性能),給出選型建議。
# 連接 telnet 127.0.0.1 11211 # 1. 狀態監控 stats # 總體統計(命中率、連接數、內存用量) stats items # 每個 slab 的 item 統計 stats slabs # slab 內存分配詳情(關注 chunk 大小、利用率) stats sizes # 所有 item 大小分佈 # 2. 存儲命令 set key flags exptime bytes\r\nvalue\r\n # 覆蓋存儲 add key flags exptime bytes\r\nvalue\r\n # 不存在才存,存在失敗 replace key flags exptime bytes\r\nvalue\r\n # 存在才替換 append key flags exptime bytes\r\nvalue\r\n # 尾部追加 prepend key flags exptime bytes\r\nvalue\r\n # 頭部前綴 cas key flags exptime bytes cas_unique\r\nvalue\r\n # 檢查並設置(樂觀鎖) incr key value # 數值自增 decr key value # 數值自減 # 3. 獲取命令 get key # 獲取單個 gets key1 key2 # 獲取多個(返回 CAS token) # 4. 刪除/清理 delete key # 刪除單個 flush_all # 清空所有數據(不釋放內存,僅標記過期)
關鍵參數: flags 用戶自定義標識(如標記壓縮/序列化方式),exptime 過期時間(Unix 時間戳或相對秒數,0=永不過期),bytes 值長度。
commons-pool、slf4jSockIOPool),支持一致性哈希、故障轉移、權重分配client.set/get/add/delete// 核心配置
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(new String[]{"10.90.11.142:11211", "10.90.11.142:11212"});
pool.setFailover(true); pool.setInitConn(10); pool.setMinConn(5); pool.setMaxConn(250);
pool.setMaxIdle(1000*60*60*3); pool.setNagle(false); pool.setSocketTO(3000);
pool.setAliveCheck(true); pool.initialize();
MemCachedClient client = new MemCachedClient();
client.add("key", "value"); // 同步阻塞
OperationFuture,支持 get() 同步阻塞或異步回調spymemcached-2.10.2.jarMemcachedClient client = new MemcachedClient(new InetSocketAddress("10.90.11.142", 11211));
OperationFuture future = client.add("spy", 0, "value");
future.get(); // 同步等待結果
// 異步回調風格
future = client.set("spy", 0, "newVal");
MemcachedClient 接口,XMemcachedClient 實現xmemcached-x.x.x.jar(無額外依賴)MemcachedClient client = new XMemcachedClient("10.90.11.142", 11211);
client.add("key", 0, "value"); // 同步調用
client.set("key", 0, "newValue");
String val = client.get("key");
client.delete("key");
| 場景 | 推薦客戶端 | 理由 |
|---|---|---|
| 老項目維護、追求零風險穩定 | Danga | 經過無數生產驗證,社區成熟 |
| 新項目、高并發、追求性能與現代架構 | XMemcached | NIO 異步底層、同步 API、無 Spy 故障轉移 Bug、淘寶血統 |
| 需要異步非阻塞 API、Future/回調風格 | SpyMemcached (需修復故障轉移) | 真正的異步 API,但必須解決單點故障數據丟失問題 |
user:10001:profile,便於分類管理與過期清理JSON (Jackson/Gson) 或 Protobuf,避免 Java 序列化跨語言/版本兼容性問題Memcached 协议簡單,命令記住增刪改查 + 統計即可。Java 客戶端選型:老項目用 Danga,新項目首選 XMemcached,避開 SpyMemcached 故障轉移坑。配合合理的 Key 設計、序列化、防穿透策略,發揮純內存 KV 極致性能。