(1)緩存介紹
- 代理服務器端緩存作用
減少後端壓力,提高網站併發延時 - 緩存常見類型
服務器端緩存:代理緩存,獲取服務器端內容進行緩存
瀏覽器端緩存 nginx
代理緩存:proxy_cache
(2)代理緩存配置
- 緩存配置
#vim /usr/local/nginx/conf/nginx.conf
upstream node {
server 192.9.191.31:8081;
server 192.9.191.31:8082;
}
proxy_cache_path /cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name www.test.com;
index index.html;
location / {
proxy_pass http://node;
proxy_cache 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;
}
}
- 參數詳解
proxy_cache_path /soft/cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
#proxy_cache //存放緩存臨時文件
#levels //按照兩層目錄分級
#keys_zone //開闢空間名,10m:開闢空間大小,1m可存放8000key
#max_size //控制最大大小,超過後Nginx會啓用淘汰規則
#inactive //60分鐘沒有被訪問緩存會被清理
#use_temp_path //臨時文件,會影響性能,建議關閉
proxy_cache 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;
#proxy_cache //開啓緩存
#proxy_cache_valid //狀態碼200|304的過期爲12h,其餘狀態碼10分鐘過期
#proxy_cache_key //緩存key
#add_header //增加頭信息,觀察客戶端respoce是否命中
#proxy_next_upstream //出現502-504或錯誤,會跳過此臺服務器訪問下一臺服務器
- 創建緩存目錄
mkdir /cache
nginx -t
nginx -s reload
- 驗證
(3)清除緩存
rm
刪除已緩存的數據
rm -rf /cache/*
- 通過
ngx_cache_purge
擴展模塊清理,需要編譯安裝nginx
(4)部分頁面不緩存
nginx
配置
#vim /usr/local/nginx/conf/nginx.conf
upstream node {
server 192.9.191.31:8081;
server 192.9.191.31:8082;
}
proxy_cache_path /cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name www.test.com;
index index.html;
if ($request_uri ~ ^/(static|login|register|password)) {
set $cookie_nocache 1;
}
location / {
proxy_pass http://node;
proxy_cache 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;
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pargma $http_authorization;
}
}
- 重啓加驗證
nginx -t
nginx -s reload
兩次都沒有命中
(5)統計日誌命中率
- 日誌格式:變量
$upstream_cache_status
#vim /usr/local/nginx/conf/nginx.conf
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"';
access_log logs/access.log main;
error_log logs/error.log;
- 查看日誌
- 統計日誌命中率加入到計劃任務中這裏省略
awk '{if($NF = "HIT"){count++;}} END{printf "%.2f%",count/NR*100}' /usr/local/nginx/logs/access.log