【轉載請註明出處】:http://www.javashuo.com/article/p-pureehwv-n.htmlhtml
ngx_http_limit_conn_module是Nginx提供的鏈接數限流模塊,是對某個KEY對應的總的網絡鏈接數進行限流。能夠按照IP來限制IP維度的總鏈接數,或者按照服務域名來限制某個域名的總鏈接數。但不是每個請求鏈接都會被計數器統計,只有那些被Nginx處理的且已經讀取了整個請求頭的請求鏈接纔會被計數器統計。前端
http { limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn_log_level error; limit_conn_status 503; ... server { ... location /limit { limit_conn addr 1; }
$binary_remote_addr
,其表示IP地址,也可使用如$server_name
做爲KEY來限制域名級別的最大鏈接數;語法是limit_conn_zone $variable zone=name:size;
$variable
定義鍵,zone=name定義區域名稱,size定義各個鍵共享內存空間大小。$remote_addr
變量的長度爲7字節到15字節,而存儲狀態在32位平臺中佔用32字節或64字節,在64位平臺中佔用64字節。$binary_remote_addr
變量的長度是固定的4字節,存儲狀態在32位平臺中佔用32字節或64字節,在64位平臺中佔用64字節。
1M共享空間能夠保存3.2萬個32位的狀態,1.6萬個64位的狀態。
若是共享內存空間被耗盡,服務器將會對後續全部的請求返回 503 (Service Temporarily Unavailable) 錯誤。nginx
具體能夠參考官方文檔說明ngx_http_limit_conn_modulesegmentfault
limt_conn能夠限流某個KEY的總併發/請求數,KEY能夠根據須要變化。後端
nginx配置服務器
limit_conn_zone $binary_remote_addr zone=perip:10m; limit_conn_log_level info; limit_conn_status 503; server { listen 8000; server_name localhost; location /limit { limit_conn perip 2; # add_header Content-Type "text/plain;charset=utf-8"; # return 200 "Your IP:$remote_addr"; proxy_pass http://127.0.0.1:8081; } }
容許每一個IP最大併發鏈接數爲2。
使用AB測試工具進行測試,併發數爲5個,總的請求數爲30個:網絡
ab -n 30 -c 5 http://127.0.0.1:8000/limit/test
查看nginx access.log:併發
nginx配置函數
limit_conn_zone $server_name zone=perserver:10m; limit_conn_log_level info; limit_conn_status 503; server { listen 8000; server_name localhost; location /limit { limit_conn perserver 3; proxy_pass http://127.0.0.1:8081; } }
access.log:工具
當多個 limit_conn 指令被配置時,全部的鏈接數限制都會生效。好比,下面配置不只會限制單一IP來源的鏈接數,同時也會限制單一服務器的總鏈接數:
limit_conn_zone $binary_remote_addr zone=perip:10m; limit_conn_zone $server_name zone=perserver:10m; limit_conn_log_level info; limit_conn_status 503; server { listen 8000; server_name localhost; location /limit { limit_conn perip 2; limit_conn perserver 3; proxy_pass http://127.0.0.1:8081; } }ss
ngx_http_limit_conn_module 模塊雖然說能夠解決當前面臨的併發問題,可是會引入另一些問題的。前端若是有作LVS或反代,然後端啓用了該模塊功能,那就會有不少的503錯誤,這樣的話,能夠在前端啓用該模塊,要麼就是設置白名單。
【轉載請註明出處】:http://www.javashuo.com/article/p-pureehwv-n.html