Nginx¸ºÔØƽºâËã·¨ÉèÖ㬸ßЧÓÅ»¯ÍøվЧÀÍ·Ö·¢
nginx¸ºÔØƽºâËã·¨ÉèÖ㬸ßЧÓÅ»¯ÍøվЧÀÍ·Ö·¢
¸ÅÊö£º
ÔÚ´ó¹æÄ£WebÓ¦ÓÃÖУ¬ÎªÁËÔöÌíϵͳµÄÈÝ´íÐԺͿÉÉìËõÐÔ£¬Í¨³£»á½ÓÄɸºÔØƽºâÀ´·Ö·¢ÍøÂçÇëÇó¡£Nginx×÷Ϊһ¿î¸ßÐÔÄܵķ´ÏòÊðÀíЧÀÍÆ÷£¬¾ß±¸Ç¿Ê¢µÄ¸ºÔØƽºâ¹¦Ð§£¬¿ÉÒÔƾ֤²î±ðµÄËã·¨Õ½ÂÔÀ´¾ÙÐÐÇëÇóµÄ·Ö·¢¡£±¾ÎĽ«ÏÈÈÝNginxµÄ¸ºÔØƽºâËã·¨ÉèÖ㬲¢¸ø³öÏìÓ¦µÄ´úÂëʾÀý¡£
Ò»¡¢¸ºÔØƽºâËã·¨ÏÈÈÝ
NginxÌṩÁ˶àÖÖ¸ºÔØƽºâËã·¨£¬³£ÓõÄÓÐÒÔϼ¸ÖÖ£º
ÂÖѯ£¨Round Robin£©£ºÄ¬ÈϵÄËã·¨£¬Æ¾Ö¤ÇëÇóµÄ˳ÐòÒÀ´Î·Ö·¢µ½ºó¶ËЧÀÍÆ÷¡£
ȨÖØ£¨Weight£©£º¿ÉÒÔΪ²î±ðµÄºó¶ËЧÀÍÆ÷ÉèÖòî±ðµÄȨÖØÖµ£¬Æ¾Ö¤È¨ÖرÈÀý·Ö·¢ÇëÇó¡£
IP¹þÏ££¨IP Hash£©£ºÆ¾Ö¤¿Í»§¶ËµÄIPµØµã¾ÙÐйþÏ£ÅÌË㣬°ü¹ÜÏàͬIPµÄÇëÇ󶼷ַ¢µ½Í³Ò»Ì¨Ð§ÀÍÆ÷ÉÏ¡£
×îÉÙÅþÁ¬£¨Least Connections£©£º»ùÓÚºó¶ËЧÀÍÆ÷µÄÄ¿½ñÅþÁ¬Êý£¬½«ÇëÇó·¢Ë͵½ÅþÁ¬Êý×îÉÙµÄЧÀÍÆ÷ÉÏ¡£
¶þ¡¢Nginx¸ºÔØƽºâËã·¨ÉèÖÃʾÀý
ÒÔÏÂΪһ·ÝNginxÉèÖÃÎļþʾÀý£¬ÉèÖÃÁËËĸöºó¶ËЧÀÍÆ÷£¬²¢Ê¹Óòî±ðµÄ¸ºÔØƽºâËã·¨£º
upstream backend { # ÂÖѯËã·¨ server backend1.example.com; server backend2.example.com; server backend3.example.com; # ȨÖØËã·¨ server backend4.example.com weight=2; } server { listen 80; server_name example.com; location / { proxy_pass http://backend; # IP¹þÏ£Ëã·¨ hash $remote_addr consistent; # ×îÉÙÅþÁ¬Ëã·¨ least_conn; } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪbackendµÄÉÏÓÎЧÀÍÆ÷×飬ÆäÖаüÀ¨ÁËËĸöºó¶ËЧÀÍÆ÷¡£Ä¬ÈÏÇéÐÎÏ£¬NginxʹÓÃÂÖѯËã·¨½«ÇëÇó·Ö·¢µ½ÕâËĄ̈ЧÀÍÆ÷ÉÏ¡£
ΪÁËʹÓÃȨÖØËã·¨£¬ÎÒÃÇÔÚµÚËĸöºó¶ËЧÀÍÆ÷ÉÏÉèÖÃÁËweight=2£¬ÌåÏÖ¸ÃЧÀÍÆ÷´¦Öóͷ£ÇëÇóµÄÓÅÏȼ¶ÊÇÆäËûЧÀÍÆ÷µÄÁ½±¶¡£
ΪÁËʹÓÃIP¹þÏ£Ëã·¨£¬ÎÒÃÇÔÚlocationÉèÖÃÖÐʹÓÃÁËhashÒªº¦×Ö£¬²¢Ö¸¶¨ÁËconsistent²ÎÊý£¬ÌåÏÖÇëÇó»áƾ֤¿Í»§¶ËµÄIPµØµã¾ÙÐйþÏ£ÅÌË㣬´Ó¶øʼÖÕ½«ÏàͬIPµÄÇëÇó·Ö·¢µ½Í³Ò»Ì¨Ð§ÀÍÆ÷ÉÏ¡£
ΪÁËʹÓÃ×îÉÙÅþÁ¬Ëã·¨£¬ÎÒÃÇÔÚlocationÉèÖÃÖÐʹÓÃÁËleast_connÒªº¦×Ö£¬ÌåÏÖÇëÇó»á±»·Ö·¢µ½Ä¿½ñÅþÁ¬Êý×îÉÙµÄЧÀÍÆ÷ÉÏ¡£
Èý¡¢¸ºÔØƽºâËã·¨µÄÑ¡ÔñÓëÓÅ»¯
Ñ¡ÔñºÏÊʵĸºÔØƽºâË㷨ȡ¾öÓÚÏêϸµÄÓªÒµÐèÇóºÍϵͳÇéÐΡ£²î±ðµÄËã·¨¹ØÓÚ²î±ðµÄ³¡¾°»áÓвî±ðµÄÓÅÊƺÍÁÓÊÆ¡£ÀýÈ磬ÂÖѯËã·¨ÊʺÏÓÚ¸ºÔØƽºâЧÀÍÆ÷µÄ¸ºÔØÁ¿Ïà¶ÔƽºâµÄÇéÐΣ¬¶ø×îÉÙÅþÁ¬Ëã·¨ÊʺÏÓÚºó¶ËЧÀÍÆ÷¸ºÔز»Æ½ºâµÄÇéÐΡ£
±ðµÄ£¬ÎªÁ˽øÒ»²½ÓÅ»¯ÍøվЧÀÍ·Ö·¢£¬ÎÒÃÇ»¹¿ÉÒÔ˼Á¿ÒÔϼ¸µã£º
ºÏÀí·ÖÅÉȨÖØ£ºÆ¾Ö¤Ð§ÀÍÆ÷µÄÐÔÄÜÉèÖúÍ×ÊÔ´ÏÞÖÆ£¬ºÏÀí·ÖÅÉЧÀÍÆ÷µÄȨÖØÖµ£¬Ê¹µÃ¸÷¸öЧÀÍÆ÷Äܹ»³ä·ÖʹÓÃÆä×ÊÔ´¡£
¶¯Ì¬µ÷½âȨÖØ£º¿ÉÒÔƾ֤ЧÀÍÆ÷µÄ¸ºÔØÇéÐΣ¬¶¯Ì¬µ÷½âЧÀÍÆ÷µÄȨÖØÖµ£¬ÒÔʵÏÖ¸üϸÄåµÄ¸ºÔØƽºâ¡£NginxÌṩÁËupstreamÄ£¿éµÄAPI½Ó¿Ú£¬¿ÉÒÔͨ¹ý½ÅÔÀ´¶¯Ì¬ÐÞ¸ÄÉèÖÃÎļþ£¬´Ó¶øʵÏÖȨÖصĶ¯Ì¬µ÷½â¡£
ÔöÌí¿µ½¡¼ì²é£º¿ÉÒÔ°´ÆÚ¶Ôºó¶ËЧÀÍÆ÷¾ÙÐпµ½¡¼ì²é£¬ÒÔÅжÏЧÀÍÆ÷µÄ¿ÉÓÃÐÔ¡£NginxÌṩÁËhealth_checkÄ£¿é£¬¿ÉÒÔÉèÖÃ×Ô¶¯¼à²âºó¶ËЧÀÍÆ÷µÄ¿µ½¡×´Ì¬£¬²¢Æ¾Ö¤ÏÖÕæÏàÐξÙÐÐÏìÓ¦µÄ´¦Öóͷ£¡£
×ܽ᣺
ͨ¹ýºÏÀíÉèÖÃNginxµÄ¸ºÔØƽºâËã·¨£¬¿ÉÒÔÌá¸ßÍøվЧÀ͵ĿÉÓÃÐÔºÍÐÔÄÜ¡£Æ¾Ö¤Ïêϸ³¡¾°ºÍÐèÇóÑ¡ÔñÊʺϵÄËã·¨£¬²¢Æ¾Ö¤ÏÖÕæÏàÐξÙÐÐÓÅ»¯ºÍµ÷½â£¬½«ÓÐÓÃÌáÉýÍøÕ¾µÄ¸ºÔØÄÜÁ¦ºÍÓû§ÌåÑé¡£
ÒÔÉÏÊǹØÓÚNginx¸ºÔØƽºâËã·¨ÉèÖõÄÏÈÈÝ£¬Ï£Íû¶Ô¸÷ÈËÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇNginx¸ºÔØƽºâËã·¨ÉèÖ㬸ßЧÓÅ»¯ÍøվЧÀÍ·Ö·¢µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡