高效能、分散式記憶體快取系統,適用於:
sudo apt-get update
sudo apt-get install memcached
# 手動啟動 (生產環境建議用 systemd)
memcached -p 11211 -m 256 -d -u memcache -l 127.0.0.1
# 參數說明
# -p 11211 監聽埠 (預設 11211)
# -m 256 記憶體上限 256 MB
# -d 背景 daemon 模式
# -u memcache 執行使用者 (安全性)
# -l 127.0.0.1 只綁定本地介面 (安全性)
# -vv 詳細日誌 (除錯用)
# 編輯 /etc/memcached.conf 設定參數
# -m 512
# -p 11211
# -l 127.0.0.1
sudo systemctl enable memcached
sudo systemctl start memcached
sudo systemctl status memcached
telnet localhost 11211
# 連線後輸入:
set mykey 0 60 5
hello
# STORED
get mykey
# VALUE mykey 0 5
# hello
# END
quit
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version> <!-- 請用最新版 -->
</dependency>
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.AddrUtil;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class MemcachedUtil {
private static final MemcachedClient client;
private static final int DEFAULT_EXPIRY = 3600; // 1小時
private static final int OP_TIMEOUT_MS = 2000; // 操作超時 2秒
static {
try {
// 支援多節點:AddrUtil.getAddresses("host1:11211 host2:11211")
client = new MemcachedClient(AddrUtil.getAddresses("localhost:11211"));
// 連線失敗快速失敗設定
client.getConfig().setOperationTimeout(OP_TIMEOUT_MS);
} catch (IOException e) {
throw new ExceptionInInitializerError("Memcached 客戶端初始化失敗: " + e.getMessage());
}
}
/** 設定快取 (同步阻塞等待結果) */
public static boolean set(String key, Object value) {
return set(key, value, DEFAULT_EXPIRY);
}
public static boolean set(String key, Object value, int expirySeconds) {
try {
Future<Boolean> future = client.set(key, expirySeconds, value);
return future.get(OP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logError("set", key, e);
return false;
}
}
/** 取得快取 */
public static <T> T get(String key, Class<T> clazz) {
try {
Object value = client.get(key);
if (value == null) return null;
return clazz.cast(value);
} catch (Exception e) {
logError("get", key, e);
return null;
}
}
/** 刪除快取 */
public static boolean delete(String key) {
try {
Future<Boolean> future = client.delete(key);
return future.get(OP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logError("delete", key, e);
return false;
}
}
/** 關閉客戶端 (應用關閉時呼叫) */
public static void shutdown() {
client.shutdown();
}
private static void logError(String op, String key, Exception e) {
System.err.printf("[Memcached] %s key=%s error: %s%n", op, key, e.getMessage());
}
}
public class Demo {
public static void main(String[] args) {
// 存入
MemcachedUtil.set("user:1001", "{\"name\":\"John\",\"age\":30}");
MemcachedUtil.set("session:abc", new UserSession("u1001", "token-xyz"), 1800);
// 讀取
String json = MemcachedUtil.get("user:1001", String.class);
UserSession session = MemcachedUtil.get("session:abc", UserSession.class);
System.out.println("JSON: " + json);
System.out.println("Session: " + session);
// 刪除
MemcachedUtil.delete("user:1001");
MemcachedUtil.shutdown();
}
}
# application.yml
spring:
cache:
type: memcached
memcached:
servers: localhost:11211
expiration: 3600
# 依賴
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'com.google.code.simple-spring-memcached:spring-cache:4.0.0'
# 使用
@Cacheable(value = "users", key = "#id")
public User findById(Long id) { ... }
@CacheEvict(value = "users", key = "#user.id")
public void update(User user) { ... }
# 持續監看 stats
watch "echo stats | nc localhost 11211"
# 關鍵指標
# curr_items 目前項目數
# bytes 佔用記憶體位元組
# curr_connections 目前連線數
# get_hits / get_misses 命中/未命中
# evictions 被驅逐項目數 (記憶體不足)
# limit_maxbytes 記憶體上限
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.stats.MemcachedStats;
Map statsMap = client.getStats().get(OP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
for (Map.Entry entry : statsMap.entrySet()) {
String server = entry.getKey();
MemcachedStats stats = entry.getValue();
System.out.println(server + " -> 命中率: " +
(100.0 * stats.getGetHits() / (stats.getGetHits() + stats.getGetMisses())) + "%");
System.out.println(" 記憶體使用: " + stats.getBytes() + " / " + stats.getLimitMaxbytes());
}
| 問題 | 原因 | 解決方案 |
|---|---|---|
| TimeoutException | 網路延遲、GC 停頓、連線池耗盡 | 調大 operationTimeout、檢查網路、啟用連線池、監控 GC |
| 資料不一致 | 快取未同步更新 | 寫入 DB 後立即 delete/set 快取、用 CAS 操作 |
| 熱鍵導致單節點過載 | 單一 key 存取過度集中 | 本地快取 (Caffeine) + 多層快取、Key 拆分 |
| 大物件序列化慢 | Java 序列化效能差 | 改用 JSON (Jackson)、Protobuf、Kryo |
Memcached 部署簡單、效能極佳,Java 整合首選 SpyMemcached。生產環境注意:連線池管理、超時設定、序列化選擇、監控告警、多層快取策略。現代 Spring Boot 專案建議使用 spring-boot-starter-cache 抽象層,降低耦合。