nginx配置http缓存的示例:
创建缓存目录
mkdir /data/myproject/ngx_cache -p
将tmpfs挂载于ngx_cache目录上来加速缓存的读取和写入
mount -t tmpfs -o size=500M tmpfs /data/myproject/ngx_cache
nginx的配置文件, /etc/nginx/nginx.conf
http 标签中添加
proxy_cache_path /data/myproject/ngx_cache levels=1:2 keys_zone=cache_mycache:500m inactive=1d max_size=5g;
缓存路径 目录结构 缓存空间 大小 无人访问多久删除 最大缓存容量
修改配置文件, 修改添加,修改nginx的配置文件
修改location,对特定的那个http接口启用缓存功能
location /api/xxx/vx/mycache{
proxy_cache cache_mycache;
proxy_cache_valid 200 10m;
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
add_header X-Cache-Status $upstream_cache_status;
add_header X-Cache-Status-dd "cdscdsc";
proxy_pass http://local_net;
}
upstream local_net{
server localhost:8082;
}
server{
listen 8082;
server_name 127.0.0.1;
access_log /var/log/nginx/myproject.access.log main;
error_log /var/log/nginx/myproject.error.log;
access_log syslog:server=11.111.28.134:12301 graylog2_format;
error_log syslog:server=11.111.28.134:12303;
uwsgi_connect_timeout 300; #超时时间设定
uwsgi_send_timeout 300;
uwsgi_read_timeout 300;
location /api/xxx/vx/mycache {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
include uwsgi_params;
uwsgi_pass mycacheServer;
}
}
需要注意的问题:
-
nginx的proxy cache当使用到uwsgi协议时就会失效,所以直接在location里面配置时会发现缓存并没有起作用。
为了使缓存奏效,可以在nginx上再进行一次转发,通过本地转本地的方式,来保证缓存有效。 -
后端服务返回头设置不允许缓存,或者设置过期时间是过去某个时刻,nginx也不会去缓存。
解决方法有两种:
一是修改后端服务返回的响应头信息。
二是直接在nginx里面进行配置,忽略掉这些响应头的信息,即设置proxy_ignore_headers项。
参考文章:
https://www.cnblogs.com/oldxu/p/8626424.html
https://blog.csdn.net/dengjiexian123/article/details/53386586
https://www.cnblogs.com/chenpython123/p/11974576.html
http://www.simonzhang.net/?p=2063
https://www.jb51.net/article/95945.htm
https://www.cnblogs.com/ghl1024/p/9013805.html