nginx缓存

通常情况下缓存是用来减少后端压力,将压力尽可能的往前推,减少后端压力,提高网络并发延时!

1. 缓存常见类型

服务端缓存
20200627144904

代理缓存
20200627145024

客户端缓存

20200627150917

Nginx代理缓存原理

20200627151018

2. 缓存配置语法

proxy_cache配置语法

Syntax:	proxy_cache	zone | off;
Default: proxy_cache off;
Context: http, server, location
//缓存路径
Syntax:	proxy_cache_path path [levels=levels]
[use_temp_path=on|off]	keys_zone=name:size	[inactive=time]
[max_size=size]	[manager_files=number]	[manager_sleep=time][manager_threshold=time]
[loader_files=number] [loader_sleep=time] [loader_threshold=time]	[purger=on|off]
[purger_files=number] [purger_sleep=time] [purger_threshold=time];
Default: —
Context: http

缓存过期周期

Syntax:	proxy_cache_valid [code	...] time;
Default: —
Context: http, server, location
//示例
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;

缓存的维度

Syntax:	proxy_cache_key	string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, location
//示例
proxy_cache_key	"$host$request_uri	$cookie_user";
proxy_cache_key	$scheme$proxy_host$uri$is_args$args;

3. 缓存配置实践

3.1 环境准备

OS service IP
Centos 7.2 Nginx Proxy 192.168.1.1
Centos 7.2 Nginx web 192.168.1.2

3.2 web节点准备

$ mkdir -p /soft/code{1..3}
$ for i in {1..3};do echo Code1-Url$i > /soft/code1/url$i.html;done	
$ for i in {1..3};do echo Code2-Url$i > /soft/code2/url$i.html;done
$ for i in {1..3};do echo Code3-Url$i > /soft/code3/url$i.html;done

$ vim /etc/nginx/conf.d/web_node.conf
 server {
    listen 8081;
    root /soft/code1;
    index index.html;
}

server {
    listen 8082;
    root /soft/code2;
    index index.html;
}

server {
    listen 8083;
    root /soft/code3;
    index index.html;
}
$ nginx -t
$ systemctl start nginx
$ ss -lnt | grep 80
LISTEN     0      128          *:8081                     *:*                  
LISTEN     0      128          *:8082                     *:*                  
LISTEN     0      128          *:8083                     *:*     

3.3 代理缓存配置

$ mkdir /soft/cache -p   # 创建缓存所需目录
$ vim /etc/nginx/conf.d/proxy_cache.conf
upstream cache {
    server 192.168.1.2:8081;
    server 192.168.1.2:8082;
    server 192.168.1.2:8083;
}

proxy_cache_path /soft/cache levels=1:2 keys_zone=code_cache:10m max_size=10g inactive=60m use_temp_path=off;
# proxy_cache_path: 存放缓存临时文件
# levels=1:2:按照两层目录分级
# keys_zone=code_cache:10m:开辟空间名, 10m:开辟空间大小, 1m可存放8000key
# max_size=10g:控制最大大小,超过后Nginx会启动淘汰规则
# inactive=60m:60分钟没有被访问缓存就会被清理
# use_temp_path=off:临时文件,会影响性能,建议关闭

server {
    listen 80;
    server_name 192.168.1.1;

        location / {
            proxy_pass http://cache;
            proxy_cache code_cache;   # proxy_cache:开启缓存
            proxy_cache_valid 200 304 12h;
            proxy_cache_valid any 10m;  # proxy_cache_valid:状态码200|304的过期时间为12h,其余状态码过期时间为10分钟
            add_header  Nginx-Cache "$upstream_cache_status";  # add_header:添加头部信息,观察客户端respoce是否命中
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;  # proxy_next_upstream:出>现500、502、503、504等错误页面,会跳过此台服务器访问下台
            include proxy_params;
    }
}
$ nginx -t
$ systemctl start nginx

3.4 客户端测试

$ curl -s -I http://192.168.1.1/url1.html | grep "Nginx-Cache"
Nginx-Cache: MISS
# MISS表示没有命中缓存
$ curl -s -I http://192.168.1.1/url1.html | grep "Nginx-Cache"
Nginx-Cache: HIT
# HIT表示命中缓存

4. 缓存清理实践

清理proxy_cache代理缓存!

4.1 rm删除已缓存数据

$ rm -rf /soft/cache/*
$ curl -s -I http://192.168.1.1/url1.html | grep "Nginx-Cache"
Nginx-Cache: MISS

4.2 通过ngx_cache_pruge扩展模块,需要编译安装Nginx

$ mkdir /soft/src && cd /soft/src  # 创建响应目录
$ wget http://nginx.org/download/nginx-1.12.2.tar.gz   # 下载Nginx包
$ tar xf nginx-1.12.2.tar.gz   
$ wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz    # 下载ngx_cache_purge
$ tar xf ngx_cache_purge-2.3.tar.gz       # 下载ngx_cache_purge
$ cd nginx-1.12.2/ && ./configure \
--prefix=/server/nginx --add-module=../ngx_cache_purge-2.3 \
--with-http_stub_status_module --with-http_ssl_module
$ make && make install
# 需要将上面的缓存proxy_cache.conf文件拷贝源码包中,并增加如下内容
	location ~  /purge(/.*)	{
		allow 127.0.0.1;
		allow 192.168.1.0/24;
		deny all;
		proxy_cache_purge code_cache $host$1$is_args$args;
	}

$ /server/nginx/sbin/nginx -t
$ /server/nginx/sbin/nginx -s reload
# 检测配置重新加载

举例说明:浏览器访问http://192.168.1.1/url1.html ,访问http://192.168.1.1/purge/url1.html 清除url1.html页面缓存的内容!

5. 部分页面不缓存

指定部分页面不进行proxy-cache缓存!

$ vim /etc/nginx/conf.d/proxy_cache.conf
upstream cache {
	server	192.168.1.2:8081;
	server	192.168.1.2:8082;
	server	192.168.1.3:8083;
}
proxy_cache_path /soft/cache levels=1:2 keys_zone=code_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
	listen 80;
	server_name	192.168.1.1;
	if	($request_uri ~ ^/(url3|login|register|password)) {
		set $cookie_nocache	1;    # 访问的url包含url3|login|register|password这些关键字的不进行缓存
	}
	
	location / {
		proxy_pass	http://cache;
		proxy_cache	code_cache;
		proxy_cache_valid 200 304 12h;
		proxy_cache_valid any 10m;
		proxy_cache_key	$host$uri$is_args$args; 
		proxy_no_cache	$cookie_nocache $arg_nocache $arg_comment;        # 注意此行
		proxy_no_cache	$http_pargma $http_authorization;              # 注意此行
		add_header	Nginx-Cache	"$upstream_cache_status";
		proxy_next_upstream	error timeout invalid_header http_500 http_502 http_503 http_504;
		include	proxy_params;
	}
}
$ nginx -t
$ systemtl reload nginx

$ curl -s -I http://192.168.1.1/url3.html | grep "Nginx-Cache"
Nginx-Cache: MISS
$ curl -s -I http://192.168.1.1/url3.html | grep "Nginx-Cache"
Nginx-Cache: MISS
# 测试访问定义不缓存的内容,从结果看出确实不缓存了

$ curl -s -I http://192.168.1.1/url1.html | grep "Nginx-Cache"
Nginx-Cache: MISS
$ curl -s -I http://192.168.1.1/url1.html | grep "Nginx-Cache"
Nginx-Cache: HIT
# 原本的内容依然会被缓存

6. 缓存日志记录统计


通过日志记录proxy_cache命中情况与对应url

# 修改/etc/nginx/nginx.conf中log_format格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"' '"$upstream_cache_status"';
# 就是在原本的日志格式上增加$upstream_cache_status变量

# 修改proxy_cache.conf,	在server标签新增access日志
    access_log  /var/log/nginx/proxy_cache.log main;

# 使用curl访问,最后显示日志命令情况!
192.168.1.2 - - [27/Jun/2020:16:51:30 +0800] "HEAD /url1.html HTTP/1.1" 200 0 "-" "curl/7.29.0" "-""MISS"
192.168.1.2 - - [27/Jun/2020:16:51:31 +0800] "HEAD /url1.html HTTP/1.1" 200 0 "-" "curl/7.29.0" "-""HIT"

如果需要查看nginx cache的命中率可参考Nginx cache查看命中率

posted @ 2020-11-22 23:00  吕振江  阅读(672)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end