nginx cache命中率設計
nginxは$up streamを提供しています。cachestatusという変数はキャッシュの状態を表示します。この状態を設定にhttpヘッダを追加して表示します。
・MISSが命中していないので、バックエンド・HITキャッシュに転送されることを要求したEXPIREDキャッシュが失効しました。バックエンド・UPDTINGはキャッシュを更新しています。古い応答・STALEバックエンドを使って期限切れの応答が得られます。
二、nginx cache命中率統計
即nginxは私達のために$up streamを提供してくれました。cachestatus関数は、自然に命中状態をログに書き込むことができます。具体的には以下のようにログフォーマットを定義できます。
view sourceprint
location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 180;
proxy_send_timeout 180;
proxy_read_timeout 180;
proxy_buffer_size 128k;
proxy_buffers 4 128k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
proxy_cache cache;
proxy_cache_valid 200 304 1h;
proxy_cache_valid 404 1m;
proxy_cache_key $uri$is_args$args;
add_header Nginx-Cache
"$upstream_cache_status"
・;
proxy_pass http://backend;
}
curlやブラウザで見たheaderは以下の通りです。HTTP/1.1 200 OK
Date: Mon, 22 Apr 2013 02:10:02 GMT
Server: nginx
Content-Type: image/jpeg
Content-Length: 23560
Last-Modified: Thu, 18 Apr 2013 11:05:43 GMT
Nginx-Cache: HIT
Accept-Ranges: bytes
Vary: User-Agent
$up stream_cachestatusは以下のいくつかの状態を含みます。・MISSが命中していないので、バックエンド・HITキャッシュに転送されることを要求したEXPIREDキャッシュが失効しました。バックエンド・UPDTINGはキャッシュを更新しています。古い応答・STALEバックエンドを使って期限切れの応答が得られます。
二、nginx cache命中率統計
即nginxは私達のために$up streamを提供してくれました。cachestatus関数は、自然に命中状態をログに書き込むことができます。具体的には以下のようにログフォーマットを定義できます。
log_format main
'$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'
'"$upstream_cache_status"'
;
命中率の統計方法:HITの数で日誌の総量で割るとキャッシュ命中率が得られます。awk
'{if($NF==""HIT"") hit++} END {printf "%.2f%",hit/NR}'
access.log
原理を知ると、毎日の命中率をシナリオを通じてログに集計することもできます。# crontab -l
1 0 * * * /opt/shell/nginx_cache_hit >> /usr/
local
/nginx/logs/hit
インタビューシナリオの内容は:view sourceprint
#!/bin/bash
LOG_FILE=
'/usr/local/nginx/logs/access.log.1'
LAST_DAY=$(
date
+%F -d
"-1 day"
)
awk
'{if($NF==""HIT"") hit++} END {printf "'
$LAST_DAY
': %d %d %.2f%n", hit,NR,hit/NR}'
$LOG_FILE
回転:http://www.361way.com/nginx-cache/2665.html