安装的时候注意, 添加 nginx_purge_cache 插件, 插件在这里找.
现在直接上配置:
#cache 初始设定要置于 server之外
# 代理连接超时
proxy_connect_timeout 5;
# 代理读取超时
proxy_read_timeout 60;
# 发送超时
proxy_send_timeout 5;
# Buffer / 临时文件的大小
proxy_buffer_size 16k;
proxy_buffers 4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
# !零时文件目录, 缓存创建时需要
proxy_temp_path /home/xwsoul/code/web/demo/cache/proxy_tmp/;
# !缓存文件存放目录
# levels 缓存层次
# keys_zone 缓存空间名和共享内存大小(热点内容放在内存)
# inactive 失效时间, 1d = 1天
# max_size 最大缓存空间(硬盘占用)
proxy_cache_path /home/xwsoul/code/web/demo/cache/proxy_cache/ levels=2:2 keys_zone=cache_one:20m inactive=1d max_size=2g;
# 均衡负载服务器
upstream backend {
server 127.0.0.1:81 weight=2;
server 127.0.0.2:81 weight=1;
server 127.0.0.3:81 weight=1;
}
# 代理服务器设定
server {
listen 80;
server_name demo.xwsoul.com;
root /home/xwsoul/code/web/demo;
index index.html index.php;
# 清理制定的代理生成的缓存
location ~ /purge(/*) {
allow 127.0.0.1;
allow 192.168.2.0/24;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}
location /cache {
# 代理指向地址
proxy_pass http://backend/cache;
# 调用的 cache 的命名空间
proxy_cache cache_one;
# 生成的缓存名称的 key 的名字
proxy_cache_key $host$uri$is_args$args;
# 生效值: 即代理目标的状态码以及缓存时间
proxy_cache_valid 200 304 12h;
# 其中一台负载server 发生 502 等异常时候转移到另一台负载上
proxy_next_upstream http_502 http_504 error timeout invalid_header;
# 发送头信息到客户端 - 一般是浏览器
add_header X-Cache "$upstream_cache_status $host";
# 传递的参数 - IP
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# 后端服务器设定
server {
listen 81;
# 模拟均衡负载的响应
server_name 127.0.0.1 127.0.0.2 127.0.0.3;
root /home/xwsoul/code/web/demo;
index index.html index.php;
try_files $uri @missing;
location @missing {
rewrite ^/cache/(.*) /cache/index.php?code=$1 last;
}
location ~ .*\.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}以下是 cache/index.php 的代码
<?php
//获取code,以生成不同的内容
$code = md5(isset($_GET['code'])?$_GET['code']:'');
//随机产生结果,让效果更明显
$rand = mt_rand(1, 10);
echo '<p>';
echo 'Loop <b>', $rand, '</b> :<br />';
for ($i=0;$i<$rand;$i++) {
echo $code, '<br />';
}
echo '</p>';
echo date('Ymd H:i:s'), '<br />';
缓存可以都放内存吗
如果做了内存映射, 应当是可以的