日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

如何利用nginx做代理緩存淺析_nginx

作者:不如喫茶去 ? 更新時間: 2022-02-22 編程語言

用到緩存就是為了減少后端的壓力,提高網站并發。在網站設計中,為了更好的去中心化,我們會盡量將請求集中到前端,在前端就能處理掉。

常用的緩存類型有客戶端緩存、代理緩存、服務端緩存等。

客戶端緩存【緩存存到本地,如數據存到用戶的瀏覽器緩存中,從本地讀取】代理緩存【緩存存到代理或中間件上,如從服務端獲取到的數據放置在nginx上,訪問時直接讀取nginx的緩存】服務端緩存【緩存存到服務端,經常使用redis和memchache,比如key-value格式的數據】

代理緩存簡略示意:

?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;    #跳轉到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;
    }
}

參數解釋:

  • proxy_cache_path 緩存文件路徑
  • levels 設置緩存文件目錄層次;levels=1:2 表示兩級目錄
  • keys_zone 設置緩存名字、開辟空間的大小,10m表示10 MB的大小
  • max_size 此目錄最大空間大小,10g表示10 GB的大小。假如超過了10G,nginx會根據自己的淘汰刪除規則刪除一部分緩存數據,默認覆蓋掉緩存時間最長的緩存數據。
  • inactive 在指定時間內沒人訪問則被刪除,60m表示60分鐘
  • use_temp_path 用來存放臨時文件,建議設置為off

關于更多的參數可以參考nginx官網:Module ngx_http_proxy_module:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_path

  • proxy_cache test_cache 表示已經開啟了代理緩存,若不想使用代理緩存,將該值配置成 off。
  • proxy_pass 代理的地址
  • proxy_cache_valid 200 304 12h;狀態碼為200,304的響應過期時間為 12h。
  • proxy_cache_valid any 10m;除了200和304狀態碼的其它狀態碼的緩存時間為10分鐘。
  • proxy_cache_key $host$uri$is_args$args; 設置默認緩存的key。$is_args表示請求中的URL是否帶參數,如果帶參數,$is_args值為"?"。如果不帶參數,則是空字符串。$args表示HTTP請求中的參數。
  • proxy_no_cache 當url中匹配到了 test.html , login, register, password 和 reset 時,不緩存此url所對應的頁面。

配置完畢,先檢查下語法是否正確nginx -tc /etc/nginx/nginx.conf,再重載服務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算法相似,刪除過期緩存。而如果緩存沒過期其上有服務器數據發生變化則依舊訪問是錯誤的數據。可以通過程序實現。

總結

原文鏈接:https://blog.csdn.net/qq_32737755/article/details/121969064

欄目分類
最近更新