如何利用nginx做代理緩存淺析
用到緩存就是為了減少后端的壓力,提高網(wǎng)站并發(fā)。在網(wǎng)站設(shè)計中,為了更好的去中心化,我們會盡量將請求集中到前端,在前端就能處理掉。
常用的緩存類型有客戶端緩存、代理緩存、服務(wù)端緩存等。
客戶端緩存【緩存存到本地,如數(shù)據(jù)存到用戶的瀏覽器緩存中,從本地讀取】代理緩存【緩存存到代理或中間件上,如從服務(wù)端獲取到的數(shù)據(jù)放置在nginx上,訪問時直接讀取nginx的緩存】服務(wù)端緩存【緩存存到服務(wù)端,經(jīng)常使用redis和memchache,比如key-value格式的數(shù)據(jù)】
代理緩存簡略示意:
?nginx代理緩存配置:
proxy_cache_path /opt/www/cache levels=1:2 keys_zone=test_cache:10m max_size=10g inactive=60m use_temp_path=off; server { listen 80; server_name cache.test.com; #rewrite ^/(.*)$ https://${server_name}$1 permanent; #跳轉(zhuǎn)到Https if ($request_uri ~ ^/(test.html|login|register|password|\/reset)) { set $cookie_nocache 1; } location / { proxy_cache test_cache; #要和proxy_cache_path 的 keys_zone值相等 proxy_pass http://127.0.0.1:8081; 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_pragma $http_authorization; } }
參數(shù)解釋:
- proxy_cache_path 緩存文件路徑
- levels 設(shè)置緩存文件目錄層次;levels=1:2 表示兩級目錄
- keys_zone 設(shè)置緩存名字、開辟空間的大小,10m表示10 MB的大小
- max_size 此目錄最大空間大小,10g表示10 GB的大小。假如超過了10G,nginx會根據(jù)自己的淘汰刪除規(guī)則刪除一部分緩存數(shù)據(jù),默認(rèn)覆蓋掉緩存時間最長的緩存數(shù)據(jù)。
- inactive 在指定時間內(nèi)沒人訪問則被刪除,60m表示60分鐘
- use_temp_path 用來存放臨時文件,建議設(shè)置為off
關(guān)于更多的參數(shù)可以參考nginx官網(wǎng):Module ngx_http_proxy_module:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_path
- proxy_cache test_cache 表示已經(jīng)開啟了代理緩存,若不想使用代理緩存,將該值配置成 off。
- proxy_pass 代理的地址
- proxy_cache_valid 200 304 12h;狀態(tài)碼為200,304的響應(yīng)過期時間為 12h。
- proxy_cache_valid any 10m;除了200和304狀態(tài)碼的其它狀態(tài)碼的緩存時間為10分鐘。
- proxy_cache_key $host$uri$is_args$args; 設(shè)置默認(rèn)緩存的key。$is_args表示請求中的URL是否帶參數(shù),如果帶參數(shù),$is_args值為"?"。如果不帶參數(shù),則是空字符串。$args表示HTTP請求中的參數(shù)。
- proxy_no_cache 當(dāng)url中匹配到了 test.html , login, register, password 和 reset 時,不緩存此url所對應(yīng)的頁面。
配置完畢,先檢查下語法是否正確nginx -tc /etc/nginx/nginx.conf,再重載服務(wù)nginx -s reload
附:平滑重啟nginx
[root@localhost nginx]# nginx -s reload [root@localhost nginx]# ps -elf|grep nginx 1 S root 10175 1 0 80 0 - 27830 sigsus 09:52 ? 00:00:00 nginx: master process nginx 5 S www 11165 10175 0 80 0 - 28893 ep_pol 18:10 ? 00:00:00 nginx: worker process 5 S www 11166 10175 0 80 0 - 28893 ep_pol 18:10 ? 00:00:00 nginx: worker process 5 S www 11167 10175 0 80 0 - 27830 ep_pol 18:10 ? 00:00:00 nginx: cache manager process
重啟完成這里會多一個cache manager,其主要作用和memcached的LRU算法相似,刪除過期緩存。而如果緩存沒過期其上有服務(wù)器數(shù)據(jù)發(fā)生變化則依舊訪問是錯誤的數(shù)據(jù)??梢酝ㄟ^程序?qū)崿F(xiàn)。
總結(jié)
到此這篇關(guān)于如何利用nginx做代理緩存的文章就介紹到這了,更多相關(guān)nginx做代理緩存內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。