#(1)緩存介紹 1.代理服務器端緩存做用 減小後端壓力,提升網站併發延時 2.緩存常見類型 服務器端緩存:代理緩存,獲取服務器端內容進行緩存 瀏覽器端緩存 3.nginx代理緩存:proxy_cache #(2)代理緩存配置 1.緩存配置html
#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; } }
2.參數詳解node
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或錯誤,會跳過此臺服務器訪問下一臺服務器
3.建立緩存目錄nginx
mkdir /cache nginx -t nginx -s reload
4.驗證 #(3)清除緩存 1.rm刪除已緩存的數據 rm -rf /cache/* 2.經過ngx_cache_purge擴展模塊清理,須要編譯安裝nginx #(4)部分頁面不緩存 1.nginx配置vim
#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; } }
2.重啓加驗證後端
nginx -t nginx -s reload
兩次都沒有命中 #(4)統計日誌命中率 1.日誌格式:變量$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;
2.查看日誌 3.統計日誌命中率加入到計劃任務中這裏省略緩存
awk '{if($NF = "HIT"){count++;}} END{printf "%.2f%",count/NR*100}' /usr/local/nginx/logs/access.log