1. 程式人生 > >查看nginx cache命中率

查看nginx cache命中率

使用 seo 總量 ron ali cron cal shell 狀態

一、在http header上增加命中顯示

nginx提供了$upstream_cache_status這個變量來顯示緩存的狀態,我們可以在配置中添加一個http頭來顯示這一狀態,達到類似squid的效果。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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如下:

1 2 3 4 5 6 7 8 9 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

$upstream_cache_status包含以下幾種狀態:

·MISS 未命中,請求被傳送到後端
·HIT 緩存命中
·EXPIRED 緩存已經過期請求被傳送到後端
·UPDATING 正在更新緩存,將使用舊的應答
·STALE 後端將得到過期的應答

二、nginx cache命中率統計

即然nginx為我們提供了$upstream_cache_status函數,自然可以將命中狀態寫入到日誌中。具體可以如下定義日誌格式:

1 2 3 4 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的數量除以日誌總量得出緩存命中率:

1 awk ‘{if($NF==""HIT"") hit++} END {printf "%.2f%",hit/NR}‘ access.log

了解了原理以後,也可以通過crontab腳本將每天的命中率統計到一個日誌中,以備查看。

1 2 # crontab -l 1 0 * * * /opt/shell/nginx_cache_hit >> /usr/local/nginx/logs/hit

訪腳本的內容為:

1 2 3 4 #!/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

查看nginx cache命中率