ÉîÈëÆÊÎöNginx·´ÏòÊðÀíЧÀÍÆ÷µÄÔÀíºÍÓ¦ÓÃ
ÉîÈëÆÊÎönginx·´ÏòÊðÀíЧÀÍÆ÷µÄÔÀíºÍÓ¦ÓÃ
¸ÅÊö£º
NginxÊÇÒ»¸ö¸ßÐÔÄÜ£¬¿ªÔ´µÄHTTPºÍ·´ÏòÊðÀíЧÀÍÆ÷¡£Ëü±»ÆÕ±éÓ¦ÓÃÓÚÐí¶à´óÐÍÍøÕ¾ºÍÓ¦ÓóÌÐò£¬ÓÉÓÚËü¾ßÓÐ׿ԽµÄÐÔÄܺͿÉÉìËõÐÔ¡£±¾ÎĽ«ÉîÈëÆÊÎöNginx·´ÏòÊðÀíЧÀÍÆ÷µÄÊÂÇéÔÀíºÍÓ¦Ó㬲¢ÌṩһЩ´úÂëʾÀý¡£
Ò»¡¢NginxµÄÊÂÇéÔÀí
1.1 ·´ÏòÊðÀíµÄ¿´·¨
·´ÏòÊðÀíÊÇÖ¸µ±¿Í»§¶Ë·¢ËÍÇëÇóʱ£¬ÊðÀíЧÀÍÆ÷½ÓÊÜÇëÇó²¢½«ÆäÊðÀíµ½ºó¶ËµÄЧÀÍÆ÷£¬È»ºó½«ÏìÓ¦·µ»Ø¸ø¿Í»§¶Ë¡£ºÍÕýÏòÊðÀíÏà·´£¬¿Í»§¶Ë²»ÖªµÀÇëÇó±»ÊðÀíµ½ÁËÄĸöЧÀÍÆ÷¡£
1.2 NginxµÄ·´ÏòÊðÀíÄ£¿é
NginxµÄ·´ÏòÊðÀí¹¦Ð§Í¨¹ýngx_http_proxy_moduleÄ£¿éʵÏÖ¡£¸ÃÄ£¿é½«¿Í»§¶ËµÄÇëÇóÊðÀíµ½ºó¶ËЧÀÍÆ÷£¬²¢½«ÏìӦת·¢¸ø¿Í»§¶Ë¡£Í¬Ê±£¬Nginx»¹ÌṩÁ˸ºÔØƽºâ¡¢»º´æµÈ¹¦Ð§£¬Ê¹µÃÓ¦ÓóÌÐò¿ÉÒÔ¸üºÃµØ´¦Àí´ó×ڵIJ¢·¢ÇëÇó¡£
1.3 Nginx·´ÏòÊðÀíµÄÁ÷³Ì
Nginx·´ÏòÊðÀíµÄÁ÷³ÌÈçÏ£º
£¨1£©¿Í»§¶Ë·¢ËÍÇëÇóµ½NginxЧÀÍÆ÷£»
£¨2£©NginxЧÀÍÆ÷ÎüÊÕµ½ÇëÇóºó£¬Æ¾Ö¤ÉèÖÃÎļþµÄ¹æÔò£¬½«ÇëÇóÊðÀíµ½ºó¶ËµÄЧÀÍÆ÷£»
£¨3£©ºó¶ËЧÀÍÆ÷´¦ÀíÇëÇ󣬲¢·µ»ØÏìÓ¦¸øNginxЧÀÍÆ÷£»
£¨4£©NginxЧÀÍÆ÷½«ºó¶ËЧÀÍÆ÷·µ»ØµÄÏìӦת·¢¸ø¿Í»§¶Ë¡£
¶þ¡¢Nginx·´ÏòÊðÀíµÄÓ¦ÓÃ
2.1 ¸ºÔØƽºâ
NginxµÄ·´ÏòÊðÀí¿ÉÒÔʵÏÖ¸ºÔØƽºâ£¬½«¿Í»§¶ËµÄÇëÇóÔȳƵطַ¢µ½¶à¸öºó¶ËЧÀÍÆ÷£¬ÒÔÌá¸ßϵͳµÄ²¢·¢´¦ÀíÄÜÁ¦¡£ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄÉèÖÃʾÀý£º
http { upstream backend { server backend1.example.com; server backend2.example.com; server backend3.example.com; } server { listen 80; server_name example.com; location / { proxy_pass http://backend; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬Nginx½«¿Í»§¶ËµÄÇëÇóͨ¹ýproxy_passÖ¸ÁîÊðÀíµ½ºó¶ËµÄЧÀÍÆ÷backend1.example.com¡¢backend2.example.comºÍbackend3.example.com£¬ÊµÏÖÁËÇëÇóµÄ¸ºÔØƽºâ¡£
2.2 »º´æ
NginxµÄ·´ÏòÊðÀí»¹¿ÉÒÔʵÏÖ»º´æ£¬½«ÇëÇóµÄÏìÓ¦»º´æÆðÀ´£¬¼ÓËÙ¶ÔÏàͬÇëÇóµÄÏìÓ¦ËÙÂÊ¡£ÏÂÃæÊÇÒ»¸ö¼òÆӵĻº´æÉèÖÃʾÀý£º
http { proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m; server { listen 80; server_name example.com; location / { proxy_pass http://backend; proxy_cache my_cache; proxy_cache_valid 200 1h; proxy_cache_use_stale error timeout invalid_header updating; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬NginxʹÓÃproxy_cacheÖ¸ÁÇëÇóµÄÏìÓ¦»º´æÆðÀ´£¬ÉèÖÃÎļþÖеÄproxy_cache_validÖ¸ÁîÖ¸¶¨ÁËÏìÓ¦»º´æµÄÓÐÓÃÆÚ£¬proxy_cache_use_staleÖ¸ÁîÖ¸¶¨Á˵±ºó¶ËЧÀÍÆ÷²»¿ÉÓÃʱ£¬ÊÇ·ñʹÓÃÓâÆڵĻº´æ¡£
½áÂÛ£º
±¾ÎÄÉîÈëÆÊÎöÁËNginx·´ÏòÊðÀíЧÀÍÆ÷µÄÔÀíºÍÓ¦Ó㬲¢ÌṩÁËһЩ´úÂëʾÀý¡£Í¨¹ý·´ÏòÊðÀí£¬Nginx¿ÉÒÔʵÏÖ¸ºÔØƽºâ¡¢»º´æµÈ¹¦Ð§£¬Ìá¸ßϵͳµÄÐÔÄܺͿÉÉìËõÐÔ¡£Ï£Íû±¾ÎĶԶÁÕßÃ÷È·Nginx·´ÏòÊðÀíµÄÊÂÇéÔÀíºÍÓ¦ÓÃÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇÉîÈëÆÊÎöNginx·´ÏòÊðÀíЧÀÍÆ÷µÄÔÀíºÍÓ¦ÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡