nginx.png
引言
平常我們在web服務(wù)中或多或少會用到cache爹土,這次我們說的便是nginx cache启涯。在代理層上的cache涉兽,有別于redis或memcache那種業(yè)務(wù)cache深碱,nginx cache多用于靜態(tài)資源的cache。
什么是nginx 在哪里配置cache棺蛛,我們就省略了怔蚌,我們直接講重點。
詳情
- 開啟Cache
在nginx.conf中加入如下代碼
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=STATIC:200m
inactive=24h max_size=1g;
proxy_cache_path
指的是存放cache的位置鞠值,如果沒有此文件夾媚创,重啟nginx會報錯
keys_zone=STATIC:200m
表示這個zone名稱為STATIC,分配的內(nèi)存大小為200MB
inactive=24h
表示這個zone中的緩存文件如果在1天內(nèi)都沒有被訪問彤恶,那么文件會被cache manager進程刪除掉
-
max_size=1g
表示最大緩存大小為1G
- 對于指定的域名加上cache
我們直接上實際加入的nginx配置
location ~* (/gateway/v1/phone/getAppOtherTimeNews*|/gateway/v1/phone/newscontent*) {
client_body_buffer_size 500M;
proxy_cache STATIC;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_valid 200 304 10m;
add_header Access-Control-Allow-Origin *;
proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
rewrite /gateway/v1(.+)$ $1 break;
proxy_pass http://localhost:7700;
}
location /gateway/v1 {
client_body_buffer_size 500M;
add_header Access-Control-Allow-Origin *;
proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_redirect off;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
rewrite /gateway/v1(.+)$ $1 break;
proxy_pass http://localhost:7700;
}
上面我們只對于符合 /gateway/v1/phone/getAppOtherTimeNews*|/gateway/v1/phone/newscontent*
這個正則表達式的路徑進行緩存,所以我們也只需要關(guān)注這個location里面的即可鳄橘,對于不符合此正則表達式的會自動路由到下面的訪問中声离。
這里的關(guān)鍵參數(shù)就是下面這三個。
proxy_cache STATIC;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_valid 200 304 10m;
proxy_cache
表示緩存的空間瘫怜,與前面配置的keys_zone
相符
proxy_cache_key
表示緩存的位置术徊,有點類似于索引的意思
proxy_cache_valid
則表示緩存code為200的時間為10 分鐘
這樣,我們只要把配置加上鲸湃,我們的緩存服務(wù)就OK了赠涮。