首先用的缓存是proxy_cache.

在http段里加入下列几句:

 

[plain] view plain copy
 
  1. proxy_connect_timeout 5;  
  2.   proxy_read_timeout 60;  
  3.   proxy_send_timeout 5;  
  4.   proxy_buffer_size 16k;  
  5.   proxy_buffers 4 64k;  
  6.   proxy_busy_buffers_size 128k;  
  7.   proxy_temp_file_write_size 128k;  
  8.   proxy_temp_path /home/temp_dir;  
  9.   proxy_cache_path /home/cache levels=1:2 keys_zone=cache_one:50m inactive=20m max_size=30g;  


上面的各行的参数我再时不解释,网上有很多。

 

 

接下来在要缓存的service里加入:

 

[plain] view plain copy
 
  1. location /gou/detail-id-116  {  
  2.            ##缓存  
  3.           index  index.html index.htm index.php;  
  4.           proxy_cache cache_one;  
  5.           proxy_cache_valid 200 302 1h;  
  6.             
  7.           proxy_cache_key $host$uri$is_args$args;  
  8.           proxy_pass   http://contactpool;  
  9.           proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";#不处理后端服务器返回的指定响应头  
  10.           expires 30d;  
  11.           proxy_set_header Host $host;  
  12.           proxy_set_header X-Real-IP $remote_addr;  
  13.           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
  14.        }  

 

当然可以用正则缓存更多的页面如:~.*\.(PHP|jsp|cgi)?$

上面的我只解释一下地方:

 

[plain] view plain copy
 
  1. proxy_ignore_headers  

这个表示不处理后端服务器返回的指定响应头,作用就是能够缓存动态页面,比如.php的页面,如果不加这一行就只能缓存静态的页面内容了。

 

现在:nginx -s reload 后缓存就有了,

接下来如何在需要的时候清理缓存呢,

网上一位大牛分析了nginx是如何存的缓存文件:

计算方法:
1) nginx先把请求地址/1.png用md5进行哈希,得到e0bd86606797639426a92306b1b98ad9
md5的参数就是上面的配置中:

[plain] view plain copy
 
  1. proxy_cache_key  

值,如md5("www.xxx.com/gou/detail-id-116");

2) level=1:2就是把最后一位数9拿出来建一个目录,然后再把9前面的2位建一个目录,最后把刚才得到的这个缓存文件放到9/ad目录中。
同样的方法推理,如果level=1:1,那么缓存文件的路径就是/usr/local/nginx/cache/9/d/e0bd86606797639426a92306b1b98ad9

 

那么我们就可以写一个脚本来清理特定的缓存了:

 

[plain] view plain copy
 
    1. #!/usr/bin/env php  
    2. <?php  
    3.   
    4. $cache_dir = '/usr/local/nginx/cache/';  
    5. $request_uri = $argv[1];  
    6. $url_hash = md5($request_uri);  
    7. $dir1 = substr($url_hash,-1,1) . '/';  
    8. $dir2 = substr($url_hash,-3,2) . '/';  
    9. $cached_file = $cache_dir . $dir1 . $dir2 . $url_hash;  
    10. if (is_file($cached_file)) {  
    11.     if (unlink($cache_dir . $dir1 . $dir2 . $url_hash)) {  
    12.         echo $request_uri . " 缓存清除成功\n";  
    13.     } else {  
    14.         echo $request_uri . " 缓存清除失败\n";  
    15.     }  
    16. } else {  
    17.     echo $request_uri . " 未被缓存\n";  

-----------------------------------------------------------------------------------------------------------------------

fastcgi cache

先看下测试数据:

未使用

Concurrency Level:      5
Time taken for tests:   9.016 seconds
Complete requests:      100
Failed requests:        0
Write errors:           0
Total transferred:      1696500 bytes
HTML transferred:       1669000 bytes
Requests per second:    11.09 [#/sec] (mean)
Time per request:       450.781 [ms] (mean)
Time per request:       90.156 [ms] (mean, across all concurrent requests)
Transfer rate:          183.76 [Kbytes/sec] received

日志里显示,页面执行需要0.004s

Concurrency Level:      5
Time taken for tests:   3.203 seconds
Complete requests:      100
Failed requests:        0
Write errors:           0
Total transferred:      1685400 bytes
HTML transferred:       1669000 bytes
Requests per second:    31.22 [#/sec] (mean)
Time per request:       160.156 [ms] (mean)
Time per request:       32.031 [ms] (mean, across all concurrent requests)
Transfer rate:          513.84 [Kbytes/sec] received

日志里显示,页面执行时间为0s

提高的很明显!
http里:

fastcgi_cache_path /www/php_cache  levels=1:2  keys_zone=cache_php:30m inactive=1d max_size=10g;

server里:

location ~ .*\.php?$
{
      #fastcgi_pass  unix:/tmp/php-cgi.sock;
      fastcgi_pass  127.0.0.1:9000;
      fastcgi_index index.php;
      include fcgi.conf;
      #以下是fastcgi_cache的配置
      fastcgi_cache   cache_php;
      fastcgi_cache_valid   200 302  1h;
      fastcgi_cache_min_uses  1;
      fastcgi_cache_use_stale error  timeout invalid_header http_500;
      fastcgi_cache_key $host$request_uri;
 }

fastcgi_cache_path:fastcgi_cache
缓存目录,可以设置目录层级,比如1:2会生成16*256个字目录,cache_php是这个缓存空间的名字,cache是用多少内存(这样热门的内容
nginx直接放内存,提高访问速度),inactive表示默认失效时间,max_size表示最多用多少硬盘空间。本来还有个
fastcgi_temp_path参数,但发现似乎没用。

fastcgi_cache_valid:定义哪些http头要缓存
fastcgi_cache_min_uses:URL经过多少次请求将被缓存
fastcgi_cache_use_stale:定义哪些情况下用过期缓存
fastcgi_cache_key:定义fastcgi_cache的key,示例中就以请求的URI作为缓存的key,Nginx会取这个key的md5作为缓存文件,如果设置了缓存哈希目录,Nginx会从后往前取相应的位数做为目录
fastcgi_cache:用哪个缓存空间

指定删除某一URL的php文件的缓存的PHP程序
大致代码如下:

<?php
function purgeCache()
{
    $url = $this->post('url');  //获取不带协议的url即可  如:192.168.100.121/index.php  md5为ca0523d698167fcc981bf9e04f3c792a 最终生成的文件名就是这个
  
    if (empty($url) || !Cola_Com_Validate::url($url)) {
        exit('请输入正确的URL。');
    }
 
    $md5 = md5($url);
    $cacheFile = $this->_cacheRoot . '/' . substr($md5, -2, 2) . '/' . substr($md5, -4, 2) . '/' . $md5;
 
    if (!file_exists($cacheFile)) {
        exit('缓存不存在。');
    }
 
    if (@unlink($cacheFile)) {
        echo '清除缓存成功。';
    } else {
        echo '清除缓存失败。';
    }
}

参考网站地址:http://www.fuchaoqun.com/2011/01/nginx-fastcgi_cache/

Nginx
fastcgi_cache缓存很不错,但我只想在某些页面用fastcgi_cache,很简单,有两种方法,一是在location中定义
fastcgi_cache,这样只有满足一定规则的url才会用上cache,其他的就不会了;另外一种方法是在你不需要缓存的页面上,输出禁止缓存的
头信息,用ColaPHP的话,直接$this->response->disableBrowserCache(); 具体代码:

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

这样就告诉Nginx,这个页面不需要缓存。

好吧,要淡定不要D疼,还有最后一个问题,如果页面中只有一小部分内容不可以缓存,可以用Nginx
fastcgi_cache吗?比如某个内容页,大部分内容可以缓存,但希望把用户的登录信息更新上去。答案是肯定的,可以直接输出用户未登录的页面样
式,等页面加载完毕之后,通过ajax异步更新用户信息:

$().ready(function() {
    initUser();
})