Nginx实现限流

为了防止用户的恶意访问,可以在在nginx设置限流,防止服务发生雪崩效应

 

Nginx限流分为两种

一是根据ip控制速率

二是控制并发连接数

 

1》 根据ip控制速率限流的配置

  在http模块添加配置

  

  binary_remote_addr 是一种key,表示基于 remote_addr(客户端IP) 来做限流,binary_ 的目的是压缩内存占用量。
  zone:定义共享内存区来存储访问信息, contentRateLimit:10m 表示一个大小为10M,名字为contentRateLimit的内存区域。
  1M能存储16000 IP地址的访问信息,10M可以存储16W IP地址访问信息。
  rate 用于设置最大访问速率,rate=10r/s 表示每秒最多处理10个请求。
  Nginx 实际上以毫秒为粒度来跟踪请求信息,因此 10r/s 实际上是限制:每100毫秒处理一个请求。这意味着,自上一个请求处理完后,若后续100毫秒内又有请求到达,将拒绝处理该请求.
  给某个location配置limit_req

  

       该配置的意思是 , 当请求路径是/read_content时,会根据contentRateLimit来限流,每个ip访问的速率限制是2r/s,能够突发访问的请求数量是4,不延迟处理请求。

     

完整配置如下

user  root root;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #cache
    lua_shared_dict dis_cache 128m;

    #限流设置
    limit_req_zone $binary_remote_addr zone=contentRateLimit:10m rate=2r/s;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        location /update_content {
            content_by_lua_file /root/lua/update_content.lua;
        }

        location /read_content {
            limit_req zone=contentRateLimit burst=4 nodelay;
            content_by_lua_file /root/lua/read_content.lua;
        }
    }
}

 

 2》根据并发连接数来限流

       http模块添加

  limit_conn_zone $binary_remote_addr zone=perip:10m;

  limit_conn_zone $server_name zone=perserver:10m;

 

       location 添加配置

  location / {

           limit_conn perip 10;#单个客户端ip与服务器的连接数.

           limit_conn perserver 100; #限制与服务器的总连接数

          root html; index index.html index.htm;

      }

完整配置如下

http {
    include       mime.types;
    default_type  application/octet-stream;

    #cache
    lua_shared_dict dis_cache 128m;

    #限流设置
    limit_req_zone $binary_remote_addr zone=contentRateLimit:10m rate=2r/s;

    limit_conn_zone $binary_remote_addr zone=perip:10m;

    limit_conn_zone $server_name zone=perserver:10m; 

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;
        #所有以brand开始的请求,单个客户端ip与服务端的连接数是10,总共不超过100
        location /brand {
             limit_conn perip 10;#单个客户端ip与服务器的连接数.
             limit_conn perserver 100; #限制与服务器的总连接数
             proxy_pass http://192.168.211.1:18081;
        }

        location /update_content {
            content_by_lua_file /root/lua/update_content.lua;
        }

        location /read_content {
            limit_req zone=contentRateLimit burst=4 nodelay;
            content_by_lua_file /root/lua/read_content.lua;
        }
    }
}

 

posted @ 2020-02-26 14:33  踏月而来  阅读(3056)  评论(0编辑  收藏  举报