Nginx緩存服務

Nginx緩存服務php

1.緩存常見類型
2.緩存配置語法
3.緩存配置實踐
4.緩存清理實踐
5.部分頁面不緩存
6.緩存日誌記錄統計html

一般狀況下緩存是用來減小後端壓力, 將壓力盡量的往前推, 減小後端壓力,提升網站併發延時node

客戶端 <--> nginx <---> 服務端nginx

1.緩存常見類型web

服務端緩存 --> redis / memcachedredis

代理緩存, 獲取服務端內容進行緩存 nginx_proxyshell

客戶端瀏覽器緩存vim

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查看倒很簡單瀏覽器

1、在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 後端將獲得過時的應答

2、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

相關文章
相關標籤/搜索