nginx提供了$upstream_cache_status这个变量来显示缓存的状态,我们可以在配置中添加一个http头来显示这一状态,达到类似squid的效果。 

Java代码  收藏代码

  1. location  / {  

  2.     proxy_redirect          off;  

  3.     proxy_set_header        Host            $host;  

  4.     proxy_set_header        X-Real-IP       $remote_addr;  

  5.     proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;  

  6.     proxy_connect_timeout   180;  

  7.     proxy_send_timeout      180;  

  8.     proxy_read_timeout      180;  

  9.     proxy_buffer_size       128k;  

  10.     proxy_buffers           4 128k;  

  11.     proxy_busy_buffers_size 128k;  

  12.     proxy_temp_file_write_size 128k;  

  13.     proxy_cache cache;  

  14.     proxy_cache_valid 200 304 1h;  

  15.     proxy_cache_valid 404 1m;  

  16.     proxy_cache_key $uri$is_args$args;  

  17.     add_header  Nginx-Cache "$upstream_cache_status";  

  18.     proxy_pass http://backend;  

  19. }  


Java代码  收藏代码

  1. HTTP/1.1 200 OK  

  2. Date: Mon, 22 Apr 2013 02:10:02 GMT  

  3. Server: nginx  

  4. Content-Type: p_w_picpath/jpeg  

  5. Content-Length: 23560  

  6. Last-Modified: Thu, 18 Apr 2013 11:05:43 GMT  

  7. Nginx-Cache: HIT  

  8. Accept-Ranges: bytes  

  9. Vary: User-Agent  


为了能够统计缓存的命中率,我们需要在日志中记录这一状态 

Java代码  收藏代码

  1. log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '  

  2.                   '$status $body_bytes_sent "$http_referer" '  

  3.                   '"$http_user_agent" "$http_x_forwarded_for"'  

  4.                   '"$upstream_cache_status"';  


统计方法:用HIT的数量除以日志总量得出缓存命中率: 

Java代码  收藏代码

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

  2. 30.15%  


$upstream_cache_status包含以下几种状态: 
·MISS 未命中,请求被传送到后端 
·HIT 缓存命中 
·EXPIRED 缓存已经过期请求被传送到后端 
·UPDATING 正在更新缓存,将使用旧的应答 
·STALE 后端将得到过期的应答