NginxÊðÀí»º´æ¸üÐÂÉèÖã¬ÊµÊ±ÏìÓ¦ÍøÕ¾ÄÚÈÝת±ä
nginxÊðÀí»º´æ¸üÐÂÉèÖã¬ÊµÊ±ÏìÓ¦ÍøÕ¾ÄÚÈÝת±ä
СÐò£º
Ëæ×ÅÍøÕ¾»á¼ûÁ¿µÄÒ»Ö±ÔöÌí£¬ÔõÑùÌá¸ßÍøÕ¾µÄÐÔÄܳÉΪÁËÒ»¸öÖ÷ÒªµÄÎÊÌâ¡£Nginx×÷ΪһÖÖ¸ßÐÔÄܵÄHTTPЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬ÊðÀí»º´æÊÇÆäÖеÄÒ»¸öÖ÷Òª×é³É²¿·Ö¡£ÔÚÒ»Ñùƽ³£ÔËάÖУ¬¾³£ÐèÒª¶ÔÍøÕ¾¾ÙÐÐÄÚÈݵĸüкÍÐ޸ģ¬¶øͬʱ¼á³ÖÓû§»á¼ûʱµÄÏìÓ¦ËÙÂÊ¡£±¾ÎĽ«ÏÈÈÝÔõÑùÔÚNginxÖÐÉèÖÃÊðÀí»º´æ£¬²¢ÇÒÈÃÆäÄܹ»ÊµÊ±ÏìÓ¦ÍøÕ¾ÄÚÈݵÄת±ä¡£
ÉèÖÃNginxµÄÊðÀí»º´æ
ÔÚNginxµÄÉèÖÃÎļþÖУ¬ÎÒÃÇÐèÒªÌí¼ÓÒÔÏÂÉèÖÃÀ´ÆôÓÃÊðÀí»º´æ£º
http { proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m; server { listen 80; server_name example.com; location / { proxy_pass http://backend_server; proxy_cache my_cache; proxy_cache_key $scheme$host$request_uri; proxy_cache_valid 200 304 12h; proxy_cache_use_stale updating; proxy_ignore_headers Cache-Control; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖÃÖУ¬proxy_cache_pathÖ¸¶¨ÁË»º´æÎļþµÄ´æ´¢Â·¾¶ºÍÏà¹Ø²ÎÊý¡£levels=1:2ÌåÏÖ»º´æ·¾¶µÄÌõÀíÉî¶È£¬keys_zoneΪ»º´æÃû³ÆºÍ¾ÞϸÏÞÖÆ£¬max_sizeΪ»º´æµÄ×î´ó¾Þϸ£¬inactiveΪ»º´æµÄ²»»îԾʱ¼ä¡£
ÔÚserver¶ÎÖеÄlocation²¿·Ö£¬proxy_passÖ¸¶¨Á˺ó¶ËЧÀ͵ĵص㣬proxy_cacheÖ¸¶¨ÁËʹÓõĻº´æÃû³Æ£¬proxy_cache_key½ç˵ÁË»º´æµÄ¼üÖµ£¬proxy_cache_validÉ趨ÁËÏìÓ¦ÂëΪ200ºÍ304µÄÇëÇóµÄÓÐÓÃÆÚ£¬proxy_cache_use_staleÖ¸¶¨Á˵±¸üлº´æʱÊÇ·ñʹÓþɵĻº´æÄÚÈÝ£¬proxy_ignore_headersÉèÖÃÁ˺öÂÔµÄHTTPÍ·¡£
ʹÓÃNginxµÄproxy_cache_bypassÖ¸Áîʵʱ¸üлº´æ
NginxÌṩÁËproxy_cache_bypassÖ¸Á¿ÉÒÔÓÃÓÚʵʱ¸üлº´æ¡£ÎÒÃÇ¿ÉÒÔÔÚºó¶ËЧÀÍÏìӦʱ£¬Í¨¹ýÉèÖÃÏìÓ¦µÄHTTPÍ·À´´¥·¢»º´æ¸üС£ÒÔÏÂÊÇÒ»¸öʾÀý£º
import requests def update_cache(url): headers = { 'X-Cache-Bypass': '1', } response = requests.get(url, headers=headers) return response.text
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀý´úÂëÖУ¬Í¨¹ýÉèÖÃX-Cache-BypassͷΪ1£¬ÎÒÃÇ¿ÉÒÔ¸æËßNginxÔÚÊðÀí»º´æÖÐÈƹý»º´æ£¬´Ó¶øʵʱ»ñÈ¡×îеÄÄÚÈÝ¡£
×Ô¶¯´¥·¢»º´æ¸üÐÂ
³ýÁËÊÖ¶¯´¥·¢»º´æ¸üУ¬ÎÒÃÇ»¹¿ÉÒÔͨ¹ýʹÓÃ׼ʱʹÃü»òÕßWebhookÀ´×Ô¶¯´¥·¢»º´æµÄ¸üС£ÒÔÏÂÊÇÒ»¸öʹÓÃPythonµÄWeb¿ò¼ÜFlaskºÍCeleryµÄʾÀý´úÂ룺
from flask import Flask, request from celery import Celery app = Flask(__name__) celery = Celery(app.name, broker='redis://localhost:6379/0') @app.route('/update_cache', methods=['POST']) def update_cache(): url = request.form.get('url') result = celery.send_task('tasks.update_cache', args=[url]) return 'Task submitted' @celery.task def update_cache(url): headers = { 'X-Cache-Bypass': '1', } response = requests.get(url, headers=headers) return response.text if __name__ == '__main__': app.run()
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇʹÓÃFlask½¨ÉèÁËÒ»¸ö¼òÆӵĽӿÚ/update_cache£¬Í¨¹ýPOSTÇëÇóÀ´´¥·¢»º´æµÄ¸üС£ÔÚÎüÊÕµ½ÇëÇóºó£¬ÎÒÃÇʹÓÃCeleryÀ´Òì²½Ö´Ðлº´æ¸üеÄʹÃü£¬²¢·µ»ØÏìÓ¦µÄЧ¹û¡£
½áÂÛ£º
ͨ¹ýÒÔÉϵÄÉèÖúÍʾÀý´úÂ룬ÎÒÃÇ¿ÉÒÔÔÚNginxÖÐÉèÖÃÊðÀí»º´æ£¬²¢ÇÒʵʱÏìÓ¦ÍøÕ¾ÄÚÈݵÄת±ä¡£ÕâÑù¿ÉÒÔÌá¸ßÍøÕ¾µÄÐÔÄÜ£¬Í¬Ê±ÓÖÄܹ»¿ìËÙ¸üкÍÐÞ¸ÄÍøÕ¾ÄÚÈÝ¡£
ËäÈ»£¬ÔÚÏÖʵӦÓÃÖл¹¿ÉÄÜÐèҪ˼Á¿»º´æµÄʧЧսÂÔ¡¢¸ß¿ÉÓÃÐÔÒÔ¼°Çå¾²µÈÒòËØ¡£ÔÚÏêϸÉèÖÃʱ£¬ÐèҪƾ֤ÏÖʵÐèÇó¾ÙÐе÷½â¡£Ï£Íû±¾ÎĶÔѧϰºÍÏàʶNginxÊðÀí»º´æ¸üÐÂÉèÖÃÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇNginxÊðÀí»º´æ¸üÐÂÉèÖã¬ÊµÊ±ÏìÓ¦ÍøÕ¾ÄÚÈÝת±äµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡