目录缓存清除缓存控制Nginx缓存缓存 缓存的基本思想是利用客户端访问的时间局限性,将客户端访问过的内容做一个副本,在一定时间内存放到本地,当改数据下次被访问时,不必连接到后端服务器
缓存的好处
为什么使用缓存?
nginx的缓存机制
proxy模块指令
以上nginx配置结合使用:
Http {
.
.
.
proxy_cache_path /cache/nginx levels=1:2 keys_zone=imooc_cache:10m max_size=5g inactive=60m use_temp_path=off;
.
.
.
server {
.
.
.
location /api/ {
proxy_cache imooc_cache;
proxy_pass 127.0.0.1:81/api/;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
proxy_cache_key $host$uri$is_args$args;
include proxy_params;
}
}
}
proxy_params文件的配置如下:
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;
访问一次页面,并向 http://192.168.148.168:8000/api/ 发起一个接口数据请求,查看/cache/nginx目录下的缓存结果:
[root@localhost 02]# cat 9563faff155b9fcfbf3fb1b16c253021
¿]n`ÿÿÿÿÿÿÿÿÿ´m`Džt>
KEY: 192.168.148.170/api/index.PHP
HTTP/1.1 200 OK
Date: Wed, 07 Apr 2021 13:34:55 GMT
Server: Apache/2.4.46 (Unix) php/7.4.16
X-Powered-By: PHP/7.4.16
Content-Length: 31
Connection: close
Content-Type: text/html; charset=UTF-8
this is 192.168.148.170_php_new[root@localhost 02]#
ngx_cache_purge是nginx的第三方模块,能够帮助我清除nginx中的缓存。
如果启动了缓存,没有安装这个模块(ngx_cache_purge),重启nginx会出现异常:
2021/04/18 10:15:36 [emerg] 12180#0: unknown directive “proxy_cache_purge” in /vhost/test_170.cc.conf:20
这个异常是在指示我们,找不到该指令的驱动,需要按照相关模块。
ngx_cache_purge只是nginx的第三方模块,并不是某个特殊的软件,所以我们需要对nginx重新进行编译,操作如下:
./configure --sbin-path=/usr/local/nginx/nginx --conf-path=/usr/local/nginx/nginx.conf --pid-path=/usr/local/nginx/nginx.pid --with-http_gzip_static_module --with-http_stub_status_module --with-file-aio --with-http_realip_module --with-http_ssl_module --with-pcre=/home/pcre-8.44 --with-zlib=/home/zlib-1.2.11 --with-openssl=/home/openssl-1.1.1g --add-module=/home/ngx_cache_purge-2.3
make -j2
make install
配置nginx:
location ~ /clear_cache(.*) {
allow all;
proxy_cache_purge imooc_cache $host$1$is_args$args;
}
缓存清除测试
访问:http://192.168.148.170:8000/clear_cache//api/index.php, 访问这个链接将会清除接口:http://192.168.148.170:8000//api/index.php 的缓存数据。
成功清除缓存返回结果如下
没有缓存返回结果如下
proxy_no_cache
# set 指令为变量设置,proxy_no_cache参数中的值可以设置多个,但是多个值中,只要有一个是不为0的,就会通过缓存响应数据
server
{
.
.
.
location /api/ {
set $a 0; #设置初始值
if ( $request_uri ~ /api/noapi/(.*) ){
set $a 1; #如果满足不缓存 设置为1
}
proxy_no_cache $a;//
.
.
.
}
location ~ /clear_cache(.*) {
allow all;
proxy_cache_purge imooc_cache $host$1$is_args$args;
}
}
查看proxy_cache指令详解
到此这篇关于nginx缓存以及清除缓存的使用的文章就介绍到这了,更多相关nginx缓存及清除缓存内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: nginx缓存以及清除缓存的使用
本文链接: https://www.lsjlt.com/news/165085.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-18
2024-04-17
2024-04-11
2024-04-08
2024-04-08
2024-04-03
2024-03-15
2024-03-15
2024-03-11
2024-03-08
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0