ÔõÑùʹÓÃNginx¾ÙÐÐÇëÇóÏÞËÙºÍÁ÷Á¿¿ØÖÆ
ÔõÑùʹÓÃnginx¾ÙÐÐÇëÇóÏÞËÙºÍÁ÷Á¿¿ØÖÆ
NginxÊÇÒ»¸öÇáÁ¿¼¶µÄWebЧÀÍÆ÷ºÍÊðÀíЧÀÍÆ÷£¬ÓµÓиßÐÔÄܺ͸߲¢·¢´¦ÀíÄÜÁ¦£¬ÊÊÓÃÓÚ¹¹½¨´óÐ͵ÄÂþÑÜʽϵͳ¡£ÔÚÏÖʵӦÓÃÖУ¬ÎªÁË°ü¹ÜЧÀÍÆ÷µÄÎȹÌÐÔ£¬ÎÒÃǾ³£ÐèÒª¶ÔÇëÇó¾ÙÐÐÏÞËÙºÍÁ÷Á¿¿ØÖÆ¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃnginx¾ÙÐÐÇëÇóÏÞËÙºÍÁ÷Á¿¿ØÖÆ£¬²¢Ìṩ´úÂëʾÀý¡£
ÇëÇóÏÞËÙ
ÇëÇóÏÞËÙÊÇÖ¸ÏÞÖÆÿ¸ö¿Í»§¶ËÔÚһ׼ʱ¼äÄÚÄܹ»ÌᳫµÄÇëÇóÊýÄ¿¡£ÕâÑù¿ÉÒÔ×èֹij¸ö¿Í»§¶Ë¹ýÓÚƵÈÔµØÇëÇóЧÀÍÆ÷£¬Ôì³ÉЧÀÍÆ÷×ÊÔ´µÄÌ«¹ýÏûºÄ¡£
Ê×ÏÈ£¬ÔÚNginxµÄÉèÖÃÎļþÖÐÌí¼ÓÒÔÏ´úÂ룺
http { # ½ç˵ÏÞËÙÇøÓò£¬ÒÔclient IPΪ׼ limit_req_zone $binary_remote_addr zone=limit:10m rate=10r/s; server { listen 80; # ʹÓÃlimit_reqÄ£¿éÏÞÖÆÇëÇóËÙÂÊ location / { limit_req zone=limit burst=20; proxy_pass http://backend; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖý«ÏÞÖÆÿ¸ö¿Í»§¶ËÔÚ1ÃëÄÚ×î¶àÌᳫ10¸öÇëÇó£¬Áè¼ÝÏÞÖƵÄÇëÇ󽫱»ÑÓ³Ù´¦Àí¡£
Á÷Á¿¿ØÖÆ
Á÷Á¿¿ØÖÆÊÇָͨ¹ýNginx¶ÔÇëÇó¾ÙÐе÷ÀíºÍ·ÖÁ÷£¬ÒÔµÖ´ïÓÅ»¯Ð§ÀÍÆ÷¸ºÔØ¡¢Ìá¸ßÓû§ÌåÑéµÄÄ¿µÄ¡£Í¨¹ýºÏÀí·ÖÅÉЧÀÍÆ÷×ÊÔ´£¬¿ÉÒÔ°ü¹Ü²î±ðÀàÐ͵ÄÇëÇóÄܹ»»ñµÃÊʵ±µÄ´¦Àí¡£
ÒÔÏÂÊÇÒ»¸öÁ÷Á¿¿ØÖƵÄʾÀý´úÂ룺
http { # ½ç˵ºó¶ËЧÀÍÆ÷ upstream backend { server backend1; server backend2; } server { listen 80; location /api/ { # ƾ֤ÇëÇ󷾶¾ÙÐзÖÁ÷ if ($request_uri ~* "^/api/v1/") { proxy_pass http://backend1; } if ($request_uri ~* "^/api/v2/") { proxy_pass http://backend2; } } location / { # ¾²Ì¬ÎļþÇëÇó×ßÍâµØÓ²ÅÌ try_files $uri $uri/ =404; } } }
µÇ¼ºó¸´ÖÆ
ÉÏÊöÉèÖý«Æ¾Ö¤ÇëÇóµÄ·¾¶¶ÔÁ÷Á¿¾ÙÐÐÑ¡ÔñÐÔת·¢µ½ºó¶ËЧÀÍÆ÷¡£ÀýÈ磬ÒÔ/api/v1/¿ªÍ·µÄÇëÇó½«×ª·¢µ½backend1ЧÀÍÆ÷£¬ÒÔ/api/v2/¿ªÍ·µÄÇëÇó½«×ª·¢µ½backend2ЧÀÍÆ÷¡£
¿ÉÒÔƾ֤ÏÖʵÐèÇó£¬ÍŽáNginxµÄÆäËûÄ£¿é¾ÙÐиüÖØ´óµÄÁ÷Á¿¿ØÖÆ£¬ºÃ±Èͨ¹ýHTTP»á¼ûƵÂÊ¡¢Óû§IP»òcookieµÈ¾ÙÐÐÁ÷Á¿µÄϸÄ廯¿ØÖÆ¡£
×ܽ᣺
ͨ¹ýÒÔÉÏʾÀý£¬ÎÒÃÇѧϰÁËÔõÑùʹÓÃnginx¾ÙÐÐÇëÇóÏÞËÙºÍÁ÷Á¿¿ØÖÆ¡£ÇëÇóÏÞËÙ¿ÉÒÔ×èÖ¹¶ñÒâÇëÇó¶ÔЧÀÍÆ÷Ôì³ÉÌ«¹ýѹÁ¦£¬¶øÁ÷Á¿¿ØÖÆ¿ÉÒÔƾ֤²î±ðµÄÐèÇóºÏÀí·ÖÅÉЧÀÍÆ÷×ÊÔ´£¬ÌáÉýÓû§ÌåÑ顣ͨ¹ýºÏÀíµØÉèÖÃNginx£¬ÎÒÃÇÄܹ»¸üºÃµØ°ü¹ÜЧÀÍÆ÷µÄÎȹÌÐÔºÍÐÔÄÜ¡£
ÒÔÉϾÍÊÇÔõÑùʹÓÃNginx¾ÙÐÐÇëÇóÏÞËÙºÍÁ÷Á¿¿ØÖƵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡