zoukankan      html  css  js  c++  java
  • Nginx缓存服务

    Nginx缓存服务

    1.缓存常见类型
    2.缓存配置语法
    3.缓存配置实践
    4.缓存清理实践
    5.部分页面不缓存
    6.缓存日志记录统计

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

    客户端 <--> nginx <---> 服务端

    1.缓存常见类型

    服务端缓存 --> redis / memcached

    代理缓存, 获取服务端内容进行缓存 nginx_proxy

    客户端浏览器缓存

    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.缓存配置实践

    1.缓存准备

    系统 服务 地址
    CentOS7.4 Nginx Proxy 10.0.0.3
    CentOS7.4 Nginx Web 10.0.0.7
    CentOS7.4 Nginx Web 10.0.0.8

    2.web节点准备

    # web01 和 web02的nginx配置
    [root@web01 conf.d]# vim web_node.conf
    server {
            server_name o.oldboy.com;
            listen 80;
            root /code/o;
            index index.html;
    }
    
    [root@web01 conf.d]# mkdir /code/o
    [root@web01 conf.d]# echo 'web01-7...' > /code/o/index.html
    
    [root@web02 conf.d]# mkdir /code/o
    [root@web02 conf.d]# echo 'we02-8...' > /code/o/index.html
    
    [root@web01 conf.d]# nginx -t
    [root@web01 conf.d]# systemctl restart nginx
    
    window的hosts 解析 浏览器访问o.oldboy.com
    
    # lb01 负载均衡配置
    [root@lb01 conf.d]# vim web_node_proxy.conf
    upstream web_node {
            server 172.16.1.7:80;
            server 172.16.1.8:80;
    }
    server {
            server_name o.oldboy.com;
            listen 80;
    
            location / {
                    proxy_pass http://web_node;
                    include proxy_params;
            }
    }
    
    window的hosts 解析 浏览器访问o.oldboy.com
    刷新浏览器 会轮询显示web01 web02 内容
    

    2 代理配置缓存

    [root@proxy ~]# mkdir /soft/cache -p
    [root@proxy ~]# cat /etc/nginx/conf.d/web_node_proxy_cache.conf
    upstream cache {
            server 172.16.1.7:80;
            server 172.16.1.8:80;
    }
    
    #proxy_cache存放缓存临时文件
    #levels     按照两层目录分级
    #keys_zone  开辟空间名, 10m:开辟空间大小, 1m可存放8000key
    #max_size   控制最大大小, 超过后Nginx会启用淘汰规则
    #inactive   60分钟没有被访问缓存会被清理
    #use_temp_path  临时文件, 会影响性能, 建议关闭
    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 o.oldboy.com;
    
    #proxy_cache        开启缓存
    #proxy_cache_valid  状态码200|304的过期为12h, 其余状态码10分钟过期
    #proxy_cache_key    缓存key
    #add_header         增加头信息, 观察客户端respoce是否命中
    #proxy_next_upstream 出现502-504或错误, 会跳过此台服务器访问下台
            location / {
                    proxy_pass http://cache;
                    proxy_cache code_cache;
                    proxy_cache_valid 200 304 12h;
                    proxy_cache_valid any 10m;
                    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;
            }
    }
    
    #检查是否缓存
    # 浏览器访问 o.oldboy.com 缓存之后刷新就不会轮询到第二台web02
    # 浏览F12 的 Response Headers  的  Nginx-Cache: HIT    HIT命中
    
    # 看下有没有缓存文件
    [root@lb01 conf.d]# tree /soft/cache/
    /soft/cache/
    ├── 5
    │   └── b7
    │       └── de9fff16da7ea7ed37dd24c8b0471b75
    └── f
        └── f2
            └── b091f22bf0606f1ea45da26793973f2f
    
    4 directories, 2 files
    
    

    4.缓存清理实践

    如何清理proxy_cache代理缓存
    
    1.rm删除已缓存数据
    
    [root@proxy ~]# rm -rf /soft/cache/*
    [root@proxy ~]# curl -s -I http://10.0.0.3/url3.html|grep "Nginx-Cache"
    Nginx-Cache: MISS
    
    
    1.通过ngx_cache_purge扩展模块清理, 需要编译安装Nginx
    
    //建立对应目录
    [root@proxy ~]# mkdir /soft/src
    [root@proxy ~]# cd /soft/src
    
    //下载Nginx包
    [root@proxy ~]# wget http://nginx.org/download/nginx-1.12.2.tar.gz
    [root@proxy ~]# tar xf nginx-1.12.2.tar.gz
    
    //下载ngx_cache_purge
    [root@proxy ~]# wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
    [root@proxy ~]# tar xf ngx_cache_purge-2.3.tar.gz
    
    //编译Nginx
    
    [root@nginx src]# 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
    [root@nginx src]# make && make install
    
    //需要将上文的缓存proxy_cache.conf文件拷贝至源码包中, 并增加如下内容
            location ~ /purge(/.*) {
                    allow   127.0.0.1;
                    allow   10.0.0.0/24;
                    deny    all;
                    proxy_cache_purge    code_cache $host$1$is_args$args;
            }
    
    //检测配置重新加载
    [root@nginx conf.d]# /server/nginx/sbin/nginx -t
    [root@nginx conf.d]# /server/nginx/sbin/nginx -s reload
    
    使用浏览器访问建立缓存
    http:www.o.oldboy.com/url2/index.php
    
    通过purge请求对应的缓存数据
    http:www.o.oldboy.com/purge/url2.html
    
    再次刷新就会404因为缓存内容已清理
    

    5.部分页面不缓存

    指定部分页面不进行proxy_Cache缓存
    
     cat proxy_cache.conf 
    upstream cache{
            server 172.16.1.7:80;
            server 172.16.1.8:80;
    }
    
    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 o.oldboy.com;
            if ($request_uri ~ ^/(url3|login|register|password)) {
                    set $cookie_nocache 1;
            }
    
            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;
            }
    }
    
    //清理缓存
    [root@nginx ~]# rm -rf /soft/cache/*
    
    //请求测试
    [root@nginx ~]# curl -s -I http://o.oldboy.com/url3.html|grep "Nginx-Cache"    
    Nginx-Cache: MISS
    [root@nginx ~]# curl -s -I http://o.oldboy.com/url3.html|grep "Nginx-Cache"
    Nginx-Cache: MISS
    [root@nginx ~]# curl -s -I http://o.oldboy.com/url3.html|grep "Nginx-Cache"
    Nginx-Cache: MISS
    
    

    6.缓存日志记录统计

    通过日志记录proxy_cache命中情况与对应url
    
    //修改/etc/nginx/nginx.conf中log_format格式
    log_format  main  '$http_user_agent' '$request_uri' '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for"' '"$upstream_cache_status"';
                          
    //修改proxy_cache.conf, 在server标签新增access日志
        access_log /var/log/nginx/proxy_cache.log main;
        
    
    //使用curl访问, 最后检查日志命令情况
    curl/7.29.0/url3.html192.168.56.183 - - [19/Apr/2018:11:48:43 -0400] "HEAD /url3.html HTTP/1.1" 200 0 "-" "curl/7.29.0" "-""MISS"
    curl/7.29.0/url2.html192.168.56.183 - - [19/Apr/2018:11:48:45 -0400] "HEAD /url2.html HTTP/1.1" 200 0 "-" "curl/7.29.0" "-""HIT"
    curl/7.29.0/url2.html192.168.56.183 - - [19/Apr/2018:11:48:46 -0400] "HEAD /url2.html HTTP/1.1" 200 0 "-" "curl/7.29.0" "-""HIT"
    

    扩展: nginx cache 查看命中率

    nginx在web应用上的占用率越来越高,其带的模块也越来越来。nginx_cache算是一个,虽和专业的cache工具相比略逊一筹,但毕竟部署简单,不用另装软件和资源开销,所以在web cache中也占了比重不小的一席。不过像squid和varnish等cache软件都自带的有cache查看工具,而且还可以方便的在http header上显示出是否命中。nginx主要还是做web使用。所以想要得出命中率的大小,还需要通过日志进行统计,不过想要增加header查看倒很简单

    一、在http header上增加命中显示

    nginx提供了$upstream_cache_status这个变量来显示缓存的状态,我们可以在配置中添加一个http头来显示这一状态,达到类似squid的效果。

     location  / {
            proxy_redirect          off;
            proxy_set_header        Host            $host;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_connect_timeout   180;
            proxy_send_timeout      180;
            proxy_read_timeout      180;
            proxy_buffer_size       128k;
            proxy_buffers           4 128k;
            proxy_busy_buffers_size 128k;
            proxy_temp_file_write_size 128k;
            proxy_cache cache;
            proxy_cache_valid 200 304 1h;
            proxy_cache_valid 404 1m;
            proxy_cache_key $uri$is_args$args;
            add_header  Nginx-Cache "$upstream_cache_status";
            proxy_pass http://backend;
        }
    

    而通过curl或浏览器查看到的header如下:

    HTTP/1.1 200 OK
    Date: Mon, 22 Apr 2013 02:10:02 GMT
    Server: nginx
    Content-Type: image/jpeg
    Content-Length: 23560
    Last-Modified: Thu, 18 Apr 2013 11:05:43 GMT
    Nginx-Cache: HIT
    Accept-Ranges: bytes
    Vary: User-Agent
    

    $upstream_cache_status包含以下几种状态:

    ·MISS 未命中,请求被传送到后端
    ·HIT 缓存命中
    ·EXPIRED 缓存已经过期请求被传送到后端
    ·UPDATING 正在更新缓存,将使用旧的应答
    ·STALE 后端将得到过期的应答
    

    二、nginx cache命中率统计

    即然nginx为我们提供了$upstream_cache_status函数,自然可以将命中状态写入到日志中。具体可以如下定义日志格式:

    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"';
    

    命中率统计方法:用HIT的数量除以日志总量得出缓存命中率:

    awk '{if($NF==""HIT"") hit++} END {printf "%.2f%",hit/NR}' access.log
    

    了解了原理以后,也可以通过crontab脚本将每天的命中率统计到一个日志中,以备查看。

    # crontab -l
    1 0 * * * /opt/shell/nginx_cache_hit >> /usr/local/nginx/logs/hit
    

    访脚本的内容为:

    #!/bin/bash
    LOG_FILE='/usr/local/nginx/logs/access.log.1'
    LAST_DAY=$(date +%F -d "-1 day")
    awk '{if($NF==""HIT"") hit++} END {printf "'$LAST_DAY': %d %d %.2f%n", hit,NR,hit/NR}' $LOG_FILE
    

    参考
    http://www.361way.com/nginx-cache/2665.html

    博主QQ 343264992 QQ群交流:100411237 添加时候请备注博客园
  • 相关阅读:
    hdu2476 string painter
    lightoj1422 Halloween Costumes
    cf1369D---找规律,递推
    cf1368D---贪心
    cf1373D---思维,最大子段和
    poj2279 Mr. Young's Picture Permutations
    AT2442 fohen phenomenon 差分
    poj2796 feel good 单调栈
    poj2082 terrible sets 单调栈
    洛谷P2979 cheese towers
  • 原文地址:https://www.cnblogs.com/chengkanghua/p/9821471.html
Copyright © 2011-2022 走看看