快取是高併發系統的核心支柱。本文系統整理 Nginx 兩大快取模組、Memcache 分散式快取、MySQL 記憶體表三大層面的配置、原理與選型建議。
| 特性 | proxy_cache | fastcgi_cache |
|---|---|---|
| 快取對象 | 上游伺服器回應(靜態/動態皆可) | FastCGI 應用產生的內容(通常為 PHP 動態頁) |
| 減少通訊 | Nginx ↔ 上游 | Nginx ↔ PHP-FPM |
| 減輕壓力 | 上游伺服器、網路傳輸 | PHP 進程、資料庫 |
| 適用場景 | 反向代理、CDN 邊緣、微服務網關 | PHP 動態頁面整頁快取 |
# http 區塊
proxy_temp_path /var/cache/nginx/proxy_temp;
proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
server {
listen 80;
server_name www.example.com;
location / {
proxy_cache cache_one;
proxy_cache_valid 200 304 12h;
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass https://backend;
expires 1d;
}
# 手動清除快取:訪問 /purge/實際路徑
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.0.0/16;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}
# 動態頁不快取
location ~ \.(php|jsp|cgi)$ {
proxy_pass https://backend;
}
}
# http 區塊
fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2 keys_zone=php_cache:500m inactive=2d max_size=10g;
fastcgi_cache_key "$scheme$request_method$host$uri$arg_filename$arg_x$arg_y";
server {
listen 8080;
server_name www.example.com;
location / {
root /var/www;
index index.php index.html;
}
location ~ \.php$ {
root /var/www;
fastcgi_pass 127.0.0.1:9000;
fastcgi_cache php_cache;
fastcgi_cache_valid 200 48h;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# 允許 Set-Cookie 穿透(預設快取會隱藏)
fastcgi_pass_header Set-Cookie;
}
}
levels=1:2:兩級子目錄結構,避免單目錄檔案過多影響檔案系統效能。keys_zone=name:size:共享記憶體區名稱與大小,存放快取索引(Key->Metadata)。inactive=1d:未被訪問 1 天自動刪除。max_size=30g:磁碟快取上限,超過按 LRU 淘汰。proxy_cache_purge / fastcgi_cache_purge:需編譯 ngx_cache_purge 模組或使用 OpenResty。-I 參數)。PHP App -> Memcache Client (Consistent Hashing) -> Memcache Server Pool (多節點)
CREATE TABLE `session_cache` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`session_key` CHAR(32) NOT NULL,
`data` MEDIUMTEXT NOT NULL,
`expire` INT UNSIGNED NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4;
| 特性 | MEMORY 表 | 臨時表 |
|---|---|---|
| 資料儲存 | 記憶體 | 記憶體(超過 tmp_table_size 轉磁碟) |
| 重啟後 | 結構保留(.frm),資料遺失 | 完全消失 |
| 支援 BLOB/TEXT | 不支援 | 支援 |
| 索引類型 | Hash (預設) / B-Tree | B-Tree |
| 鎖粒度 | 表鎖 | 表鎖 |
| 事務 | 不支援 | 不支援 |
fastcgi_cache(最簡單、效能最高、無代碼改動)。快取無銀彈,關鍵在於識別熱點、選對層級、設定合理 TTL、監控命中率。Nginx 兩大快取模組配置相似,核心差異在於快取對象與減壓層級;Memcache 適合分散式簡單 KV;MEMORY 表適合特定高頻小表。實務中常組合使用,構建多層防禦體系。