Web 架構中,Cache 就像萬金油,哪裡不順抹哪裡。從瀏覽器到 Web 伺服器,再到 CGI 程式與資料庫,幾乎每個環節都會做 cache:瀏覽器快取、數據快取、SQL 查詢快取等等。相對之下,fastcgi 這一層的 cache 反而少有人用。
去年年底我開始摸索 nginx 的 fastcgi_cache,過程中發現一些 Wiki 與網路上沒被提到的注意點,這裡分享出來。
從瀏覽器到資料庫的流程圖
#增加調試資訊 add_header X-Cache-CFC "$upstream_cache_status - $upstream_response_time"; fastcgi_temp_path /dev/shm/nginx_tmp; #cache 設定 fastcgi_cache_path /dev/shm/nginx_cache levels=1:2 keys_zone=cfcache:10m inactive=50m; fastcgi_cache_key "$request_method://$host$request_uri"; fastcgi_cache_methods GET HEAD; fastcgi_cache cfcache; fastcgi_cache_valid any 1d; fastcgi_cache_min_uses 1; fastcgi_cache_use_stale error timeout invalid_header http_500; fastcgi_ignore_client_abort on;
設定這些參數時要特別注意作用域。像 fastcgi_cache_path 只能寫在 http 段,而 fastcgi_cache_min_uses 可以寫在 http、server、location 三個層級,這樣就能針對每個網域、每個 location 做選擇性快取。具體作用域請查 FASTCGI 模組的官方 Wiki。
為了除錯方便,我加了一個 X-Cache-CFC 回應標頭,$upstream_cache_status 表示這次請求回應來自 cache 的狀態:
$upstream_cache_status 結果一直是 miss,一次也沒命中
程式是 Discuz! 論壇,隨便測了幾下,發現 /dev/shm/nginx_cache/ 下連目錄都沒建立,回應標頭的 X-Cache-CFC 一直是 MISS。但從行程來看,cache manager 與 cache loader 都正常運行:
root 3100 1 0 14:52 ? 00:00:00 nginx: master process /usr/sbin/nginx www-data 3101 3100 0 14:52 ? 00:00:00 nginx: worker process www-data 3102 3100 0 14:52 ? 00:00:00 nginx: cache manager process www-data 3103 3100 0 14:52 ? 00:00:00 nginx: cache loader process
只好去讀 Wiki,在 fastcgi_ignore_headers 的說明裡發現線索:
Syntax: fastcgi_ignore_headers field ...
Context: http, server, location
This directive forbids processing of the named headers from the FastCGI-server reply. It is possible to specify headers like “X-Accel-Redirect”, “X-Accel-Expires”, “Expires” or “Cache-Control”.
也就是說這些標頭會被忽略。那問題會不會是 fastcgi 回應裡就帶了類似標頭?用 strace 抓了 nginx 與 fpm 的溝通資料:
#### 為確保抓到處理該請求的行程,我把 nginx、fpm 都只開一個行程 // strace -ff -tt -s 1000 -o xxx.log -p PHPFPM-PID 14:52:07.837334 write(3, "\1\6\0\1\0\343\5\0X-Powered-By: PHP/5.3.10-1ubuntu3.5\r\nExpires: Thu, 19 Nov 1981 08:52:00 GMT\r\nCache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\nPragma: no-cache\r\nContent-type: text/html\r\n\r\nHello cfc4n1362034327\0\0\0\0\0\1\3\0\1\0\10\0\0\0\0\0\0\0\0\0\0", 256) = 256 // strace -ff -tt -s 1000 -o xxx.log -p Nginx-PID 15:05:13.265663 recvfrom(12, "\1\6\0\1\0\343\5\0X-Powered-By: PHP/5.3.10-1ubuntu3.5\r\nExpires: Thu, 19 Nov 1981 08:52:00 GMT\r\nCache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0\r\nPragma: no-cache\r\nContent-type: text/html\r\n\r\nHello cfc4n1362035113\0\0\0\0\0\1\3\0\1\0\10\0\0\0\0\0\0\0\0\0\0", 4023, 0, NULL, NULL) = 256
可以確認 fpm 確實回傳了帶 Expires 與 Cache-Control 的標頭。於是幾個疑問出現了:
先查第一個疑問。我下載了對應版本(1.1.9)的 nginx 源碼,在 http/ngx_http_upstream.c 找到了相關邏輯:
// 當 fastcgi 回應包含 Set-Cookie 時,不快取
static ngx_int_t ngx_http_upstream_process_set_cookie(ngx_http_request_t *r, ngx_table_elt_t *h, ngx_uint_t offset)
{
u = r->upstream;
if (!(u->conf->ignore_headers & NGX_HTTP_UPSTREAM_IGN_SET_COOKIE)) {
u->cacheable = 0;
}
return NGX_OK;
}
// 當回應頭包含 Expires,若過期時間大於目前伺服器時間則快取,否則不快取
static ngx_int_t ngx_http_upstream_process_expires(ngx_http_request_t *r, ngx_table_elt_t *h, ngx_uint_t offset)
{
expires = ngx_http_parse_time(h->value.data, h->value.len);
if (expires == NGX_ERROR || expires < ngx_time()) {
u->cacheable = 0;
return NGX_OK;
}
r->cache->valid_sec = expires;
return NGX_OK;
}
// 當回應頭包含 Cache-Control 時
// 【注意】值為 no-cache、no-store、private 任一者則不快取
// 【注意】值為 max-age 時會被快取,過期時間 = 系統目前時間 + max-age
if (ngx_strlcasestrn(p, last, (u_char *) "no-cache", 8 - 1) != NULL
|| ngx_strlcasestrn(p, last, (u_char *) "no-store", 8 - 1) != NULL
|| ngx_strlcasestrn(p, last, (u_char *) "private", 7 - 1) != NULL) {
u->cacheable = 0;
return NGX_OK;
}
p = ngx_strlcasestrn(p, last, (u_char *) "max-age=", 8 - 1);
...
r->cache->valid_sec = ngx_time() + n;
所以 fastcgi_cache 的規則是:回應含 Set-Cookie 不快取;含 Expires 時,過期時間大於目前時間才快取;含 Cache-Control 時,值為 no-cache / no-store / private 不快取,值為 max-age 則快取且過期時間為目前時間加 max-age。此外別忘了 fastcgi_ignore_headers 的設定,以及 nginx 自有的 X-Accel-Redirect、X-Accel-Expires、X-Accel-Charset、X-Accel-Buffering 等標頭。
// 逐個測試,每次只留一個 header
header("Expires: ".gmdate("D, d M Y H:i:s", time()+10000).' GMT');
header("Expires: ".gmdate("D, d M Y H:i:s", time()-99999).' GMT');
header("X-Accel-Expires:30");
header("Cache-Control: no-cache");
header("Cache-Control: no-store");
header("Cache-Control: private");
header("Cache-Control: max-age=10");
setcookie('cfc4n',"testaaaa");
echo 'Hello cfc4n', time();
nginx fastcgi_cache 回應 expired
nginx fastcgi_cache hit 命中
把程式精簡到只輸出 hello world,結果確實被快取了。可見不是 PHP 腳本印的。多次測試後定位到 session_start,翻源碼找到這些程式碼:
// ext/session/session.c
CACHE_LIMITER_FUNC(nocache)
{
ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
ADD_HEADER("Pragma: no-cache");
}
原來是 PHP 的 session 擴充自己輸出的,由 session.cache_limiter 參數決定輸出哪一種,預設是 nocache。把 php.ini 的 session.cache_limiter 改成 none,session 模組就不再輸出這些標頭;也可以在呼叫 session_start 之前用 session_cache_limiter 函數指定。
至於為什麼用 session 時要送這些標頭?我的猜測是:需要 session 意味著使用者與伺服器有互動,每次互動結果可能不同,因此不能快取;而且每個使用者的結果都不一樣,nginx 也不能把某人的個人化回應快取給其他人。
我翻了 session.c 這段程式碼的提交記錄:
Modified Sun Dec 12 14:16:55 1999 UTC by sas
Add cache_limiter and cache_expire options.
作者是 Sascha Schumann。關於這個奇怪的過期時間,Stack Overflow 上也有人問過 Why is “Expires” 1981?,有人說那天是他的生日。若真是如此,他 1999 年加這段程式碼時才 17 歲。我發了兩封信去問他,目前還沒回覆。N 年後,這個日期會不會成了一段奇聞佳話呢?