Memcached 是高效能分散式記憶體快取系統,掌握核心指令對開發與運維至關重要。本文系統整理儲存、讀取、狀態、進階四大類指令並附實操範例。
格式:<command> <key> <flags> <exptime> <bytes>\r\n<data>\r\n
| 參數 | 說明 |
|---|---|
| command | set/add/replace/append/prepend/cas |
| key | 查找鍵值,長度 < 250 字元 |
| flags | 客戶端自定義標記 (0-2^32-1) |
| exptime | 存活秒數,0=永不過期,>30天視為 Unix 時間戳 |
| bytes | 資料區塊位元組數 |
| data block | 實際儲存的值 |
set mykey 0 3600 10
myvalue123
STORED
特性:鍵不存在則新增,存在則覆蓋更新。使用頻率最高。
add newkey 0 3600 5
hello
STORED
特性:鍵已存在時回傳 NOT_STORED,不覆蓋。適合初始化、鎖機制。
replace existing_key 0 3600 7
newdata
STORED
特性:鍵不存在時回傳 NOT_STORED。確保只更新現有資料。
delete mykey
DELETED
不存在時回傳 NOT_FOUND。
get key1 key2 key3
VALUE key1 0 5
hello
VALUE key2 0 5
world
END
gets mykey
VALUE mykey 0 5 13
hello
END
多輸出一個數字 (CAS token),資料變更時 token 會改變,配合 cas 實現樂觀鎖。
cas mykey 0 3600 5 13
world
STORED
最後一參數必須符合 gets 取得的 token,否則回傳 EXISTS。適用於高併發計數器等場景。
stats
STAT pid 12345
STAT uptime 3600
STAT curr_items 1000
STAT total_items 5000
STAT bytes 1048576
STAT curr_connections 10
STAT total_connections 10000
STAT cmd_get 50000
STAT cmd_set 10000
STAT get_hits 45000
STAT get_misses 5000
STAT evictions 0
END
關鍵指標:get_hits/get_misses (命中率)、evictions (驅逐數)、bytes (記憶體使用)。
stats items
STAT items:1:number 100
STAT items:1:age 3600
STAT items:1:evicted 0
STAT items:2:number 50
...
END
顯示各 slab class 的項目數、平均壽命、驅逐數。
stats cachedump 1 0
ITEM key1 [10 b; 1234567890 s]
ITEM key2 [20 b; 1234567895 s]
END
slab_id:從 stats items 取得limit_num:導出筆數,0=全部⚠️ 生產環境慎用,大量資料會阻塞服務。
stats slabs:Slab 分配詳情stats sizes:項目大小分佈stats reset:重置統計計數器append mykey 0 3600 6
_world
STORED
鍵不存在回傳 NOT_STORED。不更新 flags/exptime。
prepend mykey 0 3600 6
hello_
STORED
set counter 0 0 1
1
incr counter 5
6
decr counter 2
4
值必須為 64 位無號整數,超過範圍回傳錯誤。原子操作,適合計數器。
flush_all
OK
flush_all 10
OK
| 場景 | 推薦指令 | 注意事項 |
|---|---|---|
| 快取資料寫入 | set | 設定合理 exptime,避免永久佔用記憶體 |
| 分散式鎖 | add + delete | 利用 add 原子性,釋放用 delete |
| 計數器 | incr/decr | 先用 set 初始化,原子遞增遞減 |
| 樂觀鎖更新 | gets + cas | CAS token 防止覆蓋衝突 |
| Session 儲存 | set | exptime 同 Session 生命週期 |
| 除錯檢視鍵值 | stats cachedump | 僅開發/測試環境使用 |
11211Memcached (libmemcached) 優於舊版 Memcache