Nginx·´ÏòÊðÀí»º´æË¢ÐÂÉèÖã¬ÊµÊ±¸üÐÂÍøÕ¾¾²Ì¬×ÊÔ´
nginx·´ÏòÊðÀí»º´æË¢ÐÂÉèÖã¬ÊµÊ±¸üÐÂÍøÕ¾¾²Ì¬×ÊÔ´
СÐò£º
ÔÚWeb¿ª·¢ÖУ¬¾²Ì¬×ÊÔ´ÊÇÍøÕ¾Öв»¿É»òȱµÄÒ»²¿·Ö¡£È»¶ø£¬¾³£¸üеľ²Ì¬×ÊÔ´¿ÉÄܻᵼÖÂÓû§ÔÚ»á¼ûÀú³ÌÖп´µ½¾ÉµÄ°æ±¾»òÕß¼ÓÔØËÙÂʱäÂý¡£½â¾öÕâ¸öÎÊÌâµÄÒ»¸öÓÐÓÃÒªÁìÊÇʹÓÃNginxµÄ·´ÏòÊðÀí»º´æ¹¦Ð§£¬²¢Í¨¹ýÉèÖÃʵÏÖʵʱ¸üÐÂÍøÕ¾µÄ¾²Ì¬×ÊÔ´¡£±¾ÎĽ«ÏÈÈÝÔõÑùͨ¹ýNginxµÄÉèÖÃÀ´ÊµÏÖÕâÒ»¹¦Ð§¡£
¿ªÆô·´ÏòÊðÀí»º´æ£º
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚNginxµÄÉèÖÃÖпªÆô·´ÏòÊðÀí»º´æ¡£ÕÒµ½NginxµÄÉèÖÃÎļþ£¨Í¨³£Îªnginx.conf£©²¢·¿ª£¬È»ºóÕÒµ½http½Ú£¬¼ÓÈëÒÔÏÂÉèÖãº
http { proxy_cache_path /path/to/cache/directory levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m; proxy_temp_path /path/to/temporary/directory; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_ignore_headers "Cache-Control" "Expires"; proxy_cache_valid any 10m; proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; server { ... location / { proxy_cache cache_zone; proxy_pass http://backend-server; } ... } }
µÇ¼ºó¸´ÖÆ
˵Ã÷£º
proxy_cache_path£ºÉèÖ÷´ÏòÊðÀí»º´æ·¾¶ÒÔ¼°Ïà¹ØÉèÖá£levelsÊÇĿ¼²ã¼¶£¬keys_zoneÊÇ»º´æÇøÓòµÄÃû³ÆÓë¾Þϸ£¬max_sizeÉèÖûº´æµÄ×î´ó¾Þϸ£¬inactiveÖ¸¶¨»º´æ³¬Ê±Ê±¼ä¡£
proxy_temp_path£ºÉèÖÃÔÝʱĿ¼·¾¶¡£
proxy_cache_key£ºÓÃÓÚÌìÉú»º´ækeyµÄ±äÁ¿£¬$schemeÌåÏÖÇëÇóÐÒ飬$request_methodÌåÏÖÇëÇóÒªÁ죬$hostÌåÏÖÇëÇóµÄÖ÷»úÃû£¬$request_uriÌåÏÖÇëÇóµÄURI¡£
proxy_ignore_headers£ºÖ¸¶¨ÐèÒªºöÂÔµÄÏìӦͷ¡£
proxy_cache_valid£ºÉèÖûº´æµÄÓÐÓÃʱ¼ä¡£
proxy_cache_use_stale£º½ç˵ÔÚ¸üлº´æʱÔÊÐíʹÓ󸯻º´æµÄÇéÐΡ£
ʵʱ¸üо²Ì¬×ÊÔ´£º
ÈôҪʵÏÖʵʱ¸üÐÂÍøÕ¾µÄ¾²Ì¬×ÊÔ´£¬ÎÒÃÇÐèÒªÔÚºǫ́³ÌÐò»ò¾ç±¾ÖÐÌí¼ÓÌØÁíÍâÂß¼£¬ÒÔÔÚÿ´Î¸üо²Ì¬×ÊÔ´ºó·¢³öˢлº´æµÄÇëÇó¡£ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄʾÀý£º
ÔÚºǫ́³ÌÐò»ò¾ç±¾ÖУ¬µ±¾²Ì¬×ÊÔ´±»¸üк󣬷¢³öˢлº´æµÄHTTPÇëÇó£º
import requests def refresh_cache(): url = "http://your-nginx-server/purge-url" headers = {"Host": "your-hostname"} response = requests.get(url, headers=headers) if response.status_code == 200: print("Cache refreshed successfully!") else: print("Failed to refresh cache.")
µÇ¼ºó¸´ÖÆ
NginxµÄÉèÖÃÎļþÖУ¬ÉèÖõصã·ÓÉÓ뻺´æˢУº
location ~ /purge-url { internal; proxy_cache_purge cache_zone "$scheme$request_method$host$request_uri$is_args$args"; }
µÇ¼ºó¸´ÖÆ
˵Ã÷£º
location£ºÉèÖô¦Àíˢлº´æÇëÇóµÄ·ÓÉ¡£
internal£ºÌåÏָ÷ÓÉÖ»Äܱ»ÄÚ²¿ÇëÇó»á¼û£¬ÍⲿÇëÇóÎÞ·¨»á¼û¡£
proxy_cache_purge£ºÉèÖÃҪˢеĻº´æÇøÓò¼°Ïà¹Ø²ÎÊý¡£
ͨ¹ýÒÔÉÏÉèÖ㬵±·¢³ö´øÓÐX-Purge-Cache: 1µÄGETÇëÇóµ½http://your-nginx-server/purge-urlʱ£¬Nginx»áƾ֤ÇëÇóµÄURIˢжÔÓ¦µÄ»º´æ¡£
ÑéÖ¤£º
ΪÁËÑéÖ¤ÉèÖõÄ׼ȷÐÔ£¬¿ÉÒÔʹÓÃä¯ÀÀÆ÷¡¢Postman»òÀàËƵŤ¾ßÀ´·¢³ö´øÓÐX-Purge-Cache: 1µÄGETÇëÇó¡£ÈôÊÇˢлº´æÀֳɣ¬Ôٴλá¼û¶ÔÓ¦µÄ¾²Ì¬×ÊԴʱ£¬»á´Óºó¶ËЧÀÍÆ÷»ñÈ¡×îа汾²¢¸üлº´æ£¬È·±£Óû§¿´µ½µÄÊÇ×îеľ²Ì¬×ÊÔ´¡£
½áÂÛ£º
ͨ¹ýNginxµÄ·´ÏòÊðÀí»º´æÉèÖúÍʵʱˢо²Ì¬×ÊÔ´µÄÒªÁ죬ÎÒÃÇ¿ÉÒÔÌá¸ßÍøÕ¾µÄÐÔÄܺͻá¼ûËÙÂÊ£¬²¢È·±£Óû§Äܹ»ÊµÊ±»ñÈ¡µ½×îеľ²Ì¬×ÊÔ´¡£Õâ¹ØÓÚƵÈÔ¸üеÄÍøÕ¾ÓÈΪÖ÷Òª£¬Í¬Ê±Ò²ÄܼõÇáºó¶ËЧÀÍÆ÷µÄѹÁ¦£¬Ìá¸ßÍøÕ¾µÄÎȹÌÐԺͿɿ¿ÐÔ¡£Ï£Íû±¾ÎĵÄÏÈÈݶÔÄúÓÐËù×ÊÖú£¡
ÒÔÉϾÍÊÇNginx·´ÏòÊðÀí»º´æË¢ÐÂÉèÖã¬ÊµÊ±¸üÐÂÍøÕ¾¾²Ì¬×ÊÔ´µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡