「超時」是分布式系統穩定性的基石。PHP 請求鏈路涉及 Nginx/Apache → PHP-FPM → PHP 腳本 → MySQL/Redis/HTTP API 等多層,每層都有獨立的超時機制。任一層配置不當,均會導致請求失敗、資源洩漏、甚至雪崩。本文系統梳理全鏈路超時配置、傳播機制與最佳實踐。
用戶瀏覽器
│ (客戶端超時: 瀏覽器默認 300s)
▼
Nginx / Apache (反向代理/靜態服務)
│ proxy_read_timeout / Timeout
▼
PHP-FPM (進程管理器)
│ request_terminate_timeout / request_slowlog_timeout
▼
PHP 腳本執行
│ max_execution_time / set_time_limit()
│ default_socket_timeout (流操作)
▼
下游服務
├─ MySQL: MYSQL_OPT_CONNECT_TIMEOUT / MYSQL_OPT_READ_TIMEOUT / MAX_EXECUTION_TIME
├─ Redis: redis-cli --raw / phpredis read_timeout
├─ HTTP API: cURL CURLOPT_TIMEOUT / CURLOPT_CONNECTTIMEOUT
└─ 外部服務: gRPC deadline, MQ TTL
# nginx.conf / location 塊
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
# FastCGI 專用超時
fastcgi_connect_timeout 5s; # 連接 PHP-FPM 超時
fastcgi_send_timeout 60s; # 發送請求體超時
fastcgi_read_timeout 300s; # 讀取響應超時 (關鍵!需 ≥ PHP max_execution_time)
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
}
# 通用代理超時 (若 Nginx 代理其他 HTTP 服務)
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 300s;
send_timeout 60s; # 向客戶端發送響應超時
client_body_timeout 60s; # 讀取客戶端請求體超時
client_header_timeout 60s; # 讀取客戶端請求頭超時
keepalive_timeout 65s; # Keep-Alive 空閒超時
# mod_proxy_fcgi (Apache 2.4.10+)
ProxySet timeout=300 # 總超時 (秒)
ProxyPassMatch ^/(.*\.php)$ fcgi://localhost:9000/var/www/html/$1
# mod_php (prefork)
Timeout 300 # 全局請求超時 (含請求讀取、腳本執行、響應發送)
# 或虛擬主機級
TimeOut 300
; 請求硬性終止超時 (強制 kill worker,防止卡死佔用槽位)
request_terminate_timeout = 300s ; 默認 0 (不限制),生產建議 300-600s
; 慢日誌閾值 (記錄慢請求堆棧,不終止)
request_slowlog_timeout = 10s ; 觸發慢日誌的執行時間
slowlog = /var/log/php-fpm/slow.log
; 進程管理策略
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.max_requests = 10000 ; 防記憶體洩漏,定期回收 worker
; php.ini
max_execution_time = 300 ; 腳本最大執行秒數 (CLI 默認 0 無限制)
max_input_time = 60 ; 解析 POST/GET/文件上傳數據最長秒數
memory_limit = 256M ; 內存限制
default_socket_timeout = 60 ; 流操作 (file_get_contents, fsockopen, PDO 默認) 讀取超時
; 運行時動態調整 (僅影響當前腳本)
set_time_limit(600); // 重置最大執行時間 (累計)
ini_set('max_execution_time', 600); // 同效
ini_set('default_socket_timeout', 10); // 修改流超時
關鍵區別: `max_execution_time` 只計算 CPU 時間 (不含系統調用、數據庫等待、sleep),而 `request_terminate_timeout` 是實時牆鐘時間。建議:FPM 設置略大於 PHP 設置 (如 FPM 300s, PHP 280s),由 PHP 先拋出 `Maximum execution time exceeded` 異常,便於捕獲日誌;FPM 作為最後防線強制回收進程。
<?php
$pdo = new PDO(
"mysql:host=127.0.0.1;dbname=test;charset=utf8mb4",
'user', 'pass',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
// 連接階段超時
PDO::MYSQL_ATTR_INIT_COMMAND => "SET SESSION wait_timeout=300", // 服務端空閒斷開
// PDO 本身無連接超時選項,依賴 default_socket_timeout
]
);
// 原生 mysqli 可精確控制
$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5); // 連接超時 5s
$mysqli->options(MYSQLI_OPT_READ_TIMEOUT, 30); // 讀取超時 30s
$mysqli->real_connect('127.0.0.1', 'user', 'pass', 'test', 3306);
// SQL 執行超時 (MySQL 5.7.8+ / MariaDB 10.4.6+)
$pdo->exec("SET SESSION MAX_EXECUTION_TIME=5000"); // 毫秒,僅對 SELECT 生效
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379, 2.5); // 連接超時 2.5s (浮點秒)
$redis->setOption(Redis::OPT_READ_TIMEOUT, 1.5); // 讀取超時 1.5s
$redis->setOption(Redis::OPT_WRITE_TIMEOUT, 1.5); // 寫入超時 (phpredis 5.3+)
// 管道/事務不單獨受此控制,需整體鏈路超時
// Guzzle 7+ (推薦)
$client = new GuzzleHttp\Client([
'timeout' => 10.0, // 總超時 (含連接、傳輸)
'connect_timeout' => 2.0, // 僅連接階段
'http_errors' => false, // 非 2xx 不拋異常,自行判斷
]);
$response = $client->get('https://api.example.com/data');
// 原生 cURL 精細控制
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_TIMEOUT_MS => 10000, // 總超時毫秒
CURLOPT_CONNECTTIMEOUT_MS => 2000, // 連接超時毫秒
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 3,
CURLOPT_NOSIGNAL => 1, // 多線程環境必開
]);
$result = curl_exec($ch);
理想狀態:上層超時觸發時,能取消下游進行中的操作,釋放資源。
| 場景 | Nginx fastcgi_read_timeout | FPM request_terminate_timeout | PHP max_execution_time | 下游超時 |
|---|---|---|---|---|
| 常規 CRUD API | 30s | 60s | 25s | DB 5s, Redis 0.5s, HTTP 3s |
| 大文件上傳 | 300s | 600s | 0 (CLI) / 300s | 調大讀寫超時 |
| 報表導出/異步任務 | 600s | 1200s | 0 (CLI 推薦) | DB 300s, 異步隊列無超時 |
| 高併發閃賣 | 5s | 10s | 3s | Redis 0.2s (Lua 腳本原子操作) |
| Webhook 回調 | 10s | 20s | 8s | HTTP 5s, 異步處理業務邏輯 |