ÔõÑùʵÏÖNginxµÄÏÞËÙÉèÖÃ
ÔõÑùʵÏÖNginxµÄÏÞËÙÉèÖã¬ÐèÒªÏêϸ´úÂëʾÀý
Nginx×÷Ϊһ¿î¸ßÐÔÄܵÄWebЧÀÍÆ÷ºÍ·´ÏòÊðÀíЧÀÍÆ÷£¬ÔÚÏÖʵӦÓÃÖÐÍùÍùÐèÒª¶ÔijЩ½Ó¿Ú»ò×ÊÔ´¾ÙÐÐÏÞËÙ¿ØÖÆ£¬ÒÔ°ü¹ÜϵͳµÄÎȹÌÐԺ͹«ÕýÐÔ¡£ÏÂÃ潫ÏÈÈÝÔõÑùͨ¹ýNginxµÄÉèÖÃÎļþʵÏÖÏÞËÙ¿ØÖÆ£¬²¢¸½ÉÏÏêϸµÄ´úÂëʾÀý¡£
ÉèÖÃÎļþÖнç˵ÏÞËÙÇøÓò
Ê×ÏÈÐèÒªÔÚNginxµÄÉèÖÃÎļþÖнç˵һ¸öÏÞËÙÇøÓò£¬ÓÃÓÚ´æ´¢²¢ÖÎÀíÏÞËÙµÄÏà¹ØÐÅÏ¢¡£·¿ªNginxµÄÉèÖÃÎļþ£¨Ò»Ñùƽ³£ÊÇnginx.conf»òÕßsites-available/default£©£¬ÔÚhttpÄ£¿éÄÚÌí¼ÓÒÔÏÂÉèÖãº
http { ... limit_req_zone $binary_remote_addr zone=rate_limit:10m rate=10r/s; ... }
µÇ¼ºó¸´ÖÆ
ÔÚÒÔÉÏÉèÖÃÖУ¬limit_req_zoneÓÃÓÚ½ç˵һ¸öÏÞËÙÇøÓò£¬ÆäÖÐ$binary_remote_addrÌåÏÖƾ֤¿Í»§¶ËIPµØµã¾ÙÐÐÏÞËÙ£¬zone²ÎÊýÖ¸¶¨ÁËÏÞËÙÇøÓòµÄÃû³ÆΪrate_limit£¬10mÌåÏÖÏÞËÙÇøÓòµÄÄÚ´æ¾ÞϸΪ10MB£¬rate²ÎÊýÖ¸¶¨ÁËÔÊÐíµÄ×î´óÇëÇóÊýÄ¿ÊÇÿÃë10¸ö¡£
ÉèÖÃÎļþÖÐÓ¦ÓÃÏÞËÙ
½ÓÏÂÀ´£¬ÔÚÉèÖÃÎļþÖÐÐèÒª¶ÔÏêϸµÄ½Ó¿Ú»ò×ÊÔ´¾ÙÐÐÏÞËÙ¿ØÖÆ¡£·¿ªÉèÖÃÎļþ£¬ÔÚserver¿éÄÚÌí¼ÓÒÔÏÂÉèÖãº
server { ... location /api/limited { limit_req zone=rate_limit burst=20 nodelay; ... } ... }
µÇ¼ºó¸´ÖÆ
ÔÚÒÔÉÏÉèÖÃÖУ¬locationÖ¸ÁîÌåÏÖÏÞËÙ¿ØÖÆÓ¦ÓÃÓÚ·¾¶Îª/api/limitedµÄURL¡£limit_reqÖ¸ÁîÓÃÓÚÉèÖÃÏÞËÙ¹æÔò£¬ÆäÖÐzone²ÎÊýÖ¸¶¨ÁËʹÓÃÇ°Ãæ½ç˵µÄÏÞËÙÇøÓòrate_limit£¬burst²ÎÊýÌåÏÖÔÚÁè¼ÝÏÞËÙºóÔÊÐíµÄ×î´óÇëÇóÊýÄ¿£¬nodelay²ÎÊýÌåÏÖ¹ØÓÚÁè¼ÝÏÞËÙµÄÇëÇóÊÇ·ñÁ¬Ã¦·µ»Ø¹ýʧ¡£
ÖØÔØNginxÉèÖò¢²âÊÔ
Íê³ÉÒÔÉÏÉèÖúó£¬ÉúÑÄÉèÖÃÎļþ²¢ÖØмÓÔØNginxÉèÖã¬ÒÔʹÉèÖÃÉúЧ¡£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÖØÔØNginxÉèÖãº
sudo service nginx reload
µÇ¼ºó¸´ÖÆ
È»ºó¿ÉÒÔʹÓù¤¾ß¾ÙÐвâÊÔ£¬Ä£Äâ²¢·¢ÇëÇ󣬾ÙÐÐÏÞËÙµÄЧ¹ûÑéÖ¤¡£¿ÉÒÔʹÓù¤¾ßÈçab£¨ApacheBench£©»òÕßwrk¾ÙÐвâÊÔ£¬ÀýÈ磺
ab -n 1000 -c 100 http://your-domain.com/api/limited
µÇ¼ºó¸´ÖÆ
ÉÏÊöÏÂÁîÌåÏÖ·¢ËÍ1000¸ö²¢·¢ÇëÇó£¬Ã¿´Î²¢·¢100¸öÇëÇ󣬻á¼ûURLΪhttp://your-domain.com/api/limited¡£Í¨¹ýÉó²é·µ»ØµÄ²âÊÔЧ¹û£¬¿ÉÒÔÑéÖ¤ÏÞËÙÉèÖõÄ׼ȷÐÔ¡£
ÒÔÉϾÍÊÇÔõÑùͨ¹ýNginxʵÏÖÏÞËÙÉèÖõİ취£¬Í¨¹ý½ç˵ÏÞËÙÇøÓòºÍÓ¦ÓÃÏÞËÙ¹æÔò£¬¿ÉÒÔÓÐÓÿØÖƽӿڻòÕß×ÊÔ´µÄ»á¼ûËÙÂÊ£¬¼á³ÖϵͳµÄÎȹÌÐԺ͹«ÕýÐÔ¡£Ï£ÍûÒÔÉÏÄÚÈݶÔÄãÓÐËù×ÊÖú£¡
ÒÔÉϾÍÊÇÔõÑùʵÏÖNginxµÄÏÞËÙÉèÖõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡