Nginx·´ÏòÊðÀíЧÀÍÆ÷µÄ¸ºÔØƽºâÔÀíºÍʵÏÖ·½·¨
nginx·´ÏòÊðÀíЧÀÍÆ÷µÄ¸ºÔØƽºâÔÀíºÍʵÏÖ·½·¨
Ò»¡¢¸ÅÊö
¸ºÔØƽºâÊÇÖ¸½«ÍøÂçÁ÷Á¿ÔȳƵطÖÅɵ½¶à¸öЧÀÍÆ÷ÉÏ£¬ÒÔÌá¸ßϵͳµÄÐÔÄÜ¡¢¿É¿¿ÐԺͿÉÉìËõÐÔ¡£Nginx×÷Ϊһ¿î¸ßÐÔÄܵķ´ÏòÊðÀíЧÀÍÆ÷£¬¾ß±¸Ç¿Ê¢µÄ¸ºÔØƽºâ¹¦Ð§£¬¿ÉÒÔʵÏÖÇëÇóµÄ·Ö·¢ºÍ¸ºÔØƽºâ¡£
¶þ¡¢¸ºÔØƽºâÔÀí
NginxµÄ¸ºÔØƽºâÔÀí»ùÓÚƽºâËã·¨µÄÑ¡ÔñºÍ·ÖÅÉÇëÇ󵽺ó¶ËЧÀÍÆ÷¡£³£¼ûµÄ¸ºÔØƽºâËã·¨°üÀ¨ÂÖѯ£¨round-robin£©¡¢È¨ÖØ£¨weight£©ºÍIP hashµÈ¡£
ÂÖѯ£¨round-robin£©Ëã·¨£ºNginxĬÈϽÓÄÉÂÖѯËã·¨£¬¼´½«ÇëÇó°´Ë³ÐòÒÀ´ÎµØ·Ö·¢µ½ºó¶ËµÄЧÀÍÆ÷ÉÏ¡£Ã¿¸öÇëÇ󶼻áÒÀ´Î¾ÓÉËùÓÐЧÀÍÆ÷£¬ÊµÏÖÁËÇëÇóµÄƽºâ·ÖÅÉ¡£
ȨÖØ£¨weight£©Ëã·¨£ºNginx¿ÉÒÔͨ¹ýÉèÖÃЧÀÍÆ÷µÄȨÖØÀ´ÊµÏÖ²î±ðЧÀÍÆ÷µÄ¸ºÔØƽºâ¡£È¨ÖØÔ½¸ßµÄЧÀÍÆ÷»áÊÕµ½¸ü¶àµÄÇëÇó¡£ÕâÑù¿ÉÒÔƾ֤ЧÀÍÆ÷µÄÓ²¼þ×ÊÔ´ºÍÐÔÄÜÀ´·ÖÅÉÇëÇó£¬Ìá¸ßÕûÌåµÄ¸ºÔØƽºâЧ¹û¡£
IP hashËã·¨£ºNginxʹÓÿͻ§¶ËµÄIPµØµãÀ´¾ÙÐиºÔØƽºâ£¬ÏàͬIPµÄÇëÇ󶼻á·Ö·¢µ½Í³Ò»¸öЧÀÍÆ÷ÉÏ¡£ÕâÑù¿ÉÒÔ°ü¹ÜÀ´×Ôͳһ¿Í»§¶ËµÄÇëÇó¶¼ÂäÔÚͳһ¸öЧÀÍÆ÷ÉÏ£¬ÓÃÓÚ½â¾ö»á»°¼á³ÖµÄÎÊÌâ¡£
Èý¡¢¸ºÔØƽºâµÄʵÏÖ·½·¨
ÔÚNginxÖУ¬¿ÉÒÔͨ¹ýÉèÖÃÎļþÀ´ÊµÏÖ¸ºÔØƽºâ¡£ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄʾÀý´úÂ룺
ÉèÖÃÎļþʾÀý£º
http { upstream backend { server backend1.example.com; server backend2.example.com; } server { listen 80; server_name example.com; location / { proxy_pass http://backend; } } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÉèÖÃÎļþÖУ¬Í¨¹ýupstreamÒªº¦×Ö½ç˵Á˺ó¶ËЧÀÍÆ÷×ébackend£¬¿ÉÒÔÔÚÆäÖÐö¾Ù¶à¸öЧÀÍÆ÷µØµã¡£ÔÚlocation¿éÖУ¬Ê¹ÓÃproxy_passÖ¸ÁÇëÇóת·¢µ½ºó¶ËЧÀÍÆ÷×é¡£
¸ºÔØƽºâËã·¨ÉèÖãº
¿ÉÒÔÔÚupstreamÖÐʹÓÃbalanceÒªº¦×ÖÀ´ÉèÖøºÔØƽºâËã·¨£¬ÈçÏÂËùʾ£º
upstream backend { ip_hash; server backend1.example.com; server backend2.example.com; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬Ê¹ÓÃÁËIP hashËã·¨À´¾ÙÐиºÔØƽºâ¡£
ȨÖØÉèÖãº
¿ÉÒÔÔÚupstreamÖÐʹÓÃweightÒªº¦×ÖÀ´ÉèÖÃЧÀÍÆ÷µÄȨÖØ£¬ÈçÏÂËùʾ£º
upstream backend { server backend1.example.com weight=2; server backend2.example.com weight=3; }
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬backend1.example.comµÄȨÖØΪ2£¬backend2.example.comµÄȨÖØΪ3¡£
ËÄ¡¢×ܽá
Nginx×÷Ϊһ¿î¸ßÐÔÄܵķ´ÏòÊðÀíЧÀÍÆ÷£¬¾ß±¸Ç¿Ê¢µÄ¸ºÔØƽºâ¹¦Ð§¡£Í¨¹ýʹÓÃÂÖѯ¡¢È¨ÖغÍIP hashµÈƽºâËã·¨£¬¿ÉÒÔʵÏÖÇëÇóµÄ·Ö·¢ºÍ¸ºÔØƽºâ¡£Í¨¹ýÉèÖÃÎļþµÄ·½·¨£¬¿ÉÒÔÀû±ãµØ¾ÙÐиºÔØƽºâµÄÉèÖúÍÖÎÀí¡£ÒÔÉÏÊǹØÓÚNginx¸ºÔØƽºâÔÀíºÍʵÏÖ·½·¨µÄ¼òÆÓÏÈÈÝ¡£
ÒÔÉϾÍÊÇNginx·´ÏòÊðÀíЧÀÍÆ÷µÄ¸ºÔØƽºâÔÀíºÍʵÏÖ·½·¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡