nginx实现限流 高并发处理

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毫秒内又有请求到达,将拒绝处理该请求,返回404错误。
  给某个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;
    }
    #添加nodelay配置,这样就是根据你的网络状况访问,一分钟访问够4次后,服务器直接返回503。
}}

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;

      }

完整配置如下

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;
        }
    }
}




后传:我发现我的白鞋子穿脏了以后,我对象会给我刷的很干净,所以我决定从此以后就只买白色鞋子啦。

猜你喜欢

转载自blog.csdn.net/weixin_43945983/article/details/106720933