接入層限流之ngx_http_limit_conn_module

【轉載請註明出處】: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;
    }
  • limit_conn:要配置存放KEY和計數器的共享內存區域和指定KEY的最大鏈接數;此處指定的最大鏈接數是1,表示Nginx最多同時併發處理1個鏈接;
  • limit_conn_zone:用來配置限流KEY、及存放KEY對應信息的共享內存區域大小;此處的KEY是$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

  • limit_conn_status:配置被限流後返回的狀態碼,默認返回503;
  • limit_conn_log_level:配置記錄被限流後的日誌級別,默認error級別。

具體能夠參考官方文檔說明ngx_http_limit_conn_modulesegmentfault

limit_conn的主要執行過程以下:
  1. 請求進入後首先判斷當前limit_conn_zone中相應KEY的鏈接數是否超出了配置的最大鏈接數;
  2. 若是超過了配置的最大值,則被限流,返回limit_conn_status定義的錯誤狀態碼;不然相應KEY的鏈接數加1,並註冊請求處理完成的回調函數;
  3. 進行請求處理;
  4. 在結束請求階段會調用註冊的回調函數對相應KEY的鏈接數減1。

limt_conn能夠限流某個KEY的總併發/請求數,KEY能夠根據須要變化。後端

按照IP限制併發鏈接數

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:
image.png併發

按照域名限制併發鏈接數

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:
image.png工具

當多個 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

相關文章
相關標籤/搜索