作者:Le-麦兜_738 | 来源:互联网 | 2023-09-24 01:40
缓存
缓存的基本思想是利用客户端访问的时间局限性,将客户端访问过的内容做一个副本,在一定时间内存放到本地,当改数据下次被访问时,不必连接到后端服务器反复去查询数据,而是由本地保存的副本响应数据。
保存在本地的这些副本具有一个过期时间,超过该时间将会更新。判断一个副本数据是否为过期数据的办法有很多,可以使用保留时间来判断,也可以使用数据完整度来判断。
许多Web服务器还具有校验功能,就是当某些副本数据过期以后,先向后端服务器发送校验请求,后端服务器对这些数据进行校验,如果发现原数据和副本没有差别,则将过期副本重新置为可用副本。
- 减轻服务器负载
- 提供网页响应效率
- 降低网络阻塞,增强网络可扩展性
- 服务器处理能力以及负载能力出现瓶颈,响应效率大大降低
- 为了减少网络传输延迟,提升响应效率
- 能够避免因为后端服务器出现异常以及网络故障,客户端请求数据副本能够及时响应
- nginx的缓存机制
proxy模块指令
![在这里插入图片描述](https://img6.php1.cn/3cdc5/c555/1c8/75f7933e53fc7e09.png)
以上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]
¿]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
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 的缓存数据。
成功清除缓存返回结果如下
![在这里插入图片描述](https://img6.php1.cn/3cdc5/c555/1c8/9b9fef8651e58d58.png)
没有缓存返回结果如下
![在这里插入图片描述](https://img6.php1.cn/3cdc5/c555/1c8/5ee2d72ce63fe642.png)
控制nginx缓存
server
{
.
.
.
location /api/ {
set $a 0;
if ( $request_uri ~ /api/noapi/(.*) ){
set $a 1;
}
proxy_no_cache $a;//
.
.
.
}
location ~ /clear_cache(.*) {
allow all;
proxy_cache_purge imooc_cache $host$1$is_args$args;
}
}
查看proxy_cache指令详解