萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 緩存完全指南:瀏覽器緩存、OPcache、Redis 多層加速架構

前言:為什麼需要多層緩存?

Web 請求處理鏈路:瀏覽器 → CDN → Nginx → PHP-FPM → MySQL/Redis。每一層都可引入緩存,層層遞減後端壓力。本文系統梳理 PHP 相關的四大緩存層:瀏覽器緩存、PHP Opcode 緩存、應用層資料緩存、HTTP 反向代理緩存。

一、瀏覽器緩存 (Client-Side Cache)

核心 HTTP 標頭

標頭作用範例值
Cache-Control主要控制指令max-age=3600, public, must-revalidate
Expires絕對過期時間 (HTTP/1.0 相容)Wed, 21 Oct 2025 07:28:00 GMT
Last-Modified資源最後修改時間Wed, 20 Oct 2025 12:00:00 GMT
ETag資源實體標籤 (強/弱驗證)"abc123-deadbeef"
Vary指定內容協商依據Accept-Encoding, Cookie

PHP 實作範例

<?php
// 靜態資源長期緩存 (1年) + 內容變更即失效 (ETag)
$file = __DIR__ . '/assets/app.js';
$etag = '"' . md5_file($file) . '"';
$lastMod = gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT';

header('Cache-Control: max-age=31536000, public, immutable');
header('ETag: ' . $etag);
header('Last-Modified: ' . $lastMod);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');

// 處理條件請求
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
  http_response_code(304);
  exit;
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) {
  http_response_code(304);
  exit;
}

readfile($file);

動態頁面緩存策略

<?php
// 動態頁面:短期緩存 + 必須重新驗證
header('Cache-Control: max-age=60, must-revalidate, private');
header('Vary: Accept-Encoding, Cookie'); // 不同壓縮/登入狀態分開緩存
header('ETag: ' . '"' . md5(serialize($pageData)) . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastUpdateTime) . ' GMT');

// 條件請求檢查
$etag = '"' . md5(serialize($pageData)) . '"';
if (($_SERVER['HTTP_IF_NONE_MATCH'] ?? '') === $etag) {
  http_response_code(304);
  exit;
}

防緩存 (敏感頁面/即時資料)

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache'); // HTTP/1.0 相容
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');

二、PHP Opcode 緩存 (OPcache) — 必開啟!

PHP 5.5+ 內建,將編譯後的 opcode 存入共享記憶體,省去每次請求的「解析→編譯」過程,典型提升 2-10 倍吞吐量。

生產環境推薦配置 (php.ini / php-fpm pool)

; 啟用
opcache.enable=1
opcache.enable_cli=1

; 共享記憶體大小 (視專案代碼量調整,建議 256MB-1GB)
opcache.memory_consumption=512

; 內部字串緩存
opcache.interned_strings_buffer=64

; 最大緩存檔案數 (設大於專案 PHP 檔案總數)
opcache.max_accelerated_files=20000

; 檢查腳本更新頻率 (0=每次請求檢查、生產環境建議 60-300 秒、0 開發環境)
opcache.revalidate_freq=60

; 快速關閉 (請求結束不釋放鎖,加速)
opcache.fast_shutdown=1

; 開啟優化等級 (預設 0x7FFFBFFF 全開)
opcache.optimization_level=0x7FFFBFFF

; 預載入 (PHP 7.4+) - 將常用類別/函式預載入記憶體
opcache.preload=/var/www/html/preload.php
opcache.preload_user=www-data

預載入腳本範例 (preload.php)

<?php
// 使用 opcache_compile_file 預編譯核心框架類別
$coreFiles = glob(__DIR__ . '/vendor/laravel/framework/src/Illuminate/**/*.php');
foreach ($coreFiles as $file) {
  opcache_compile_file($file);
}
// 或使用 Composer 生成的 class map
$map = require __DIR__ . '/vendor/composer/autoload_classmap.php';
foreach ($map as $file) {
  if (strpos($file, 'vendor/') !== false) opcache_compile_file($file);
}

監控與管理

  • 狀態查看:opcache_get_status() 或安裝 opcache-gui、cachetool。
  • 部署時清除:opcache_reset() 或重啟 PHP-FPM,或使用 cachetool opcache:reset。

三、應用層資料緩存 (Redis / Memcached / APCu)

選型對比

特性RedisMemcachedAPCu
資料結構豐富 (String, Hash, List, Set, SortedSet, Stream, Geo, Bitmap)單純 Key-Value單純 Key-Value
持久化RDB/AOF 可選無 (純記憶體)無 (PHP 進程生命週期)
叢集/高可用原生 Cluster、SentinelClient-side 一致性哈希單機 (PHP-FPM 多進程共享)
適用場景通用首選:Session、快取、佇列、鎖、排行榜、限流極簡 Key-Value、超大值 (>1MB)、多線程高並發單機小型應用、Opcode 以外的本地熱數據

PHP Redis 客戶端最佳實踐

<?php
// 使用 phpredis 擴展 (效能最佳) 或 predis/predis (純 PHP)
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // 高效序列化
$redis->setOption(Redis::OPT_PREFIX, 'myapp:'); // 統一前綴避免衝突

// 封裝通用快取類
class Cache {
  private Redis $redis;
  public function __construct(Redis $redis) { $this->redis = $redis; }
  
  public function get(string $key, mixed $default = null): mixed {
    $val = $this->redis->get($key);
    return $val === false ? $default : $val;
  }
  
  public function set(string $key, mixed $value, int $ttl = 3600): bool {
    return $this->redis->setex($key, $ttl, $value);
  }
  
  public function remember(string $key, int $ttl, callable $callback): mixed {
    if (($val = $this->get($key)) !== null) return $val;
    $val = $callback();
    $this->set($key, $val, $ttl);
    return $val;
  }
  
  public function delete(string $key): bool { return (bool)$this->redis->del($key); }
  public function flush(): bool { return $this->redis->flushDB(); }
}

// 使用
$cache = new Cache($redis);
$user = $cache->remember("user:{$userId}", 300, fn() => User::find($userId));

緩存策略模式

  1. Cache-Aside (旁路緩存):應用負責讀寫緩存,Cache Miss 時查 DB 回寫。最常用。
  2. Read-Through / Write-Through:緩存層代理 DB 讀寫,應用只對緩存操作 (需中間件支援)。
  3. Write-Behind (寫後):寫入緩存即返回,異步批次寫入 DB,高寫入吞吐但有數據丟失風險。
  4. 緩存擊穿/穿透/雪崩防護:
    • 擊穿:熱 Key 過期瞬間大量請求打 DB → 互斥鎖重建 (Redis SETNX) 或 永不過期 + 異步更新。
    • 穿透:查詢不存在 Key 大量請求打 DB → 布隆過濾器 或 緩存空值 (短 TTL)。
    • 雪崩:大量 Key 同期過期 → TTL 加隨機抖動 ($ttl + rand(0, 300)) + 多級緩存。

四、HTTP 反向代理緩存 (Nginx fastcgi_cache / Varnish / CDN)

Nginx fastcgi_cache 範例

# nginx.conf http 區塊
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=PHPCACHE:100m inactive=60m max_size=1g;

# server 區塊
location ~ \.php$ {
  fastcgi_pass unix:/run/php/php8.2-fpm.sock;
  fastcgi_cache PHPCACHE;
  fastcgi_cache_key "$scheme$request_method$host$request_uri";
  fastcgi_cache_valid 200 301 302 5m;   # 成功頁面緩存 5 分鐘
  fastcgi_cache_valid 404 1m;           # 404 緩存 1 分鐘
  fastcgi_cache_use_stale error timeout updating http_500 http_503;
  fastcgi_cache_bypass $http_cache_control; # 客戶端送 no-cache 時繞過
  fastcgi_no_cache $http_cache_control;
  add_header X-Cache-Status $upstream_cache_status; # HIT/MISS/BYPASS/EXPIRED
  include fastcgi_params;
}

五、壓縮傳輸 (減少頻寬、提升傳輸速度)

; php.ini / .user.ini
zlib.output_compression = On
zlib.output_compression_level = 6  ; 1-9,6 平衡 CPU/壓縮率

; 或 Nginx gzip (推薦由 Web Server 處理,卸載 PHP CPU)
# nginx.conf
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;

六、前端資源優化 (JS/CSS/圖片)

  • 版本化檔名:app.v20240115.js 或 app.[contenthash].js (Webpack/Vite 自動生成),長期強緩存 (Cache-Control: max-age=31536000, immutable)。
  • 壓縮混淆:Terser (JS)、cssnano (CSS)、ImageMagick/WebP (圖片)。
  • HTTP/2 + Server Push:減少 RTT,主動推送關鍵資源。

結語

高性能 PHP 架構 = OPcache (必開) + 瀏覽器緩存 (正確標頭) + Redis 應用層緩存 (業務熱點) + Nginx fastcgi_cache/CDN (全頁/片段緩存) + 資源版本化壓縮。各層職責清晰、失效策略明確、監控告警完備,即可支撐百萬級日活、毫秒級響應的現代化 PHP 應用。

copyright © 萬盛學電腦網 all rights reserved