V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
NGINX
NGINX Trac
3rd Party Modules
Security Advisories
CHANGES
OpenResty
ngx_lua
Tengine
在线学习资源
NGINX 开发从入门到精通
NGINX Modules
ngx_echo
lisonfan
V2EX  ›  NGINX

关于 limit_req_zone 和 limit_req 的问题

  •  
  •   lisonfan · 2018-04-06 11:36:11 +08:00 · 2758 次点击
    这是一个创建于 2183 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Nginx 的配置

    http {
      ...
      limit_req_zone $binary_remote_addr zone=allips:10m rate=100r/s;
      ...
    }
    
    server {
      ...
      limit_req zone=allips nodelay;
      ...
    }
    

    这样配置我理解为每个 IP 每秒请求不超过 100 次,每秒请求大于 100 次直接返回 503

    但是这样的配置我连 phpmyadmin 都打不开了

    求助各路大神

    dndx
        1
    dndx  
       2018-04-06 13:52:31 +08:00
    需要配置 burst,否则在打开的一瞬间,rate 看起来是无穷大,就被拒了。
    lisonfan
        2
    lisonfan  
    OP
       2018-04-06 14:00:24 +08:00
    @dndx #1
    嗯,然后我试了
    ```
    http {
    ...
    limit_req_zone $binary_remote_addr zone=allips:10m rate=100r/s;
    ...
    }

    server {
    ...
    limit_req zone=allips burst=1 nodelay;
    ...
    }
    ```
    也不行

    我现在的配置是
    ```
    http {
    ...
    limit_req_zone $binary_remote_addr zone=allips:10m rate=50r/s;
    ...
    }

    server {
    ...
    limit_req zone=allips burst=50 nodelay;
    ...
    }
    ```
    才能达到预期效果
    lisonfan
        3
    lisonfan  
    OP
       2018-04-06 14:21:57 +08:00
    @dndx #1
    看了一下 https://blog.csdn.net/hellow__world/article/details/78658041 这个资料,是不是可以这样理解
    所有的请求先放在 burst 里,如果每秒的请求量大于 burst+rate 就丢弃
    lisonfan
        4
    lisonfan  
    OP
       2018-04-06 14:41:05 +08:00
    @dndx #1
    刚说错了
    limit_req_zone 其实是设置空间的大小和 nginx 对单个 IP 的请求处理速度
    limit_req 设置的是队列的大小
    如果单个 IP 的每秒请求次数大于队列大小加上每秒限制的处理速度,超过的部分就会被拒绝
    dndx
        5
    dndx  
       2018-04-06 15:06:57 +08:00
    burst = 1 肯定不行,建议跟 rate 一致,设为 100。

    NGINX 的时间戳精度只有 1ms,对于 1ms 之内的请求看起来频率都是无穷大,所以 burst 是必须要有的。这块可以参考令牌桶算法的实现原理来理解。
    lisonfan
        6
    lisonfan  
    OP
       2018-04-06 19:23:37 +08:00
    @dndx #5
    感谢,
    还有一个问题想请教一下,关于 limit_req_zone zone size 的,
    我看官方文档( http://nginx.org/en/docs/http/ngx_http_limit_req_module.html )说:“ If the zone storage is exhausted, the least recently used state is removed. Even if after that a new state cannot be created, the request is terminated with an error.”
    看文档的这个意思貌似有点坑了,如果 10M 用完了,也无法删除历史记录的话,之后所有的请求全拒绝了。这时候只能管理员手动重启 Nginx 来解决这个问题吗?
    lisonfan
        7
    lisonfan  
    OP
       2018-04-06 19:34:45 +08:00
    @dndx #5
    刚刚看 https://www.sunzhongwei.com/limit-request-rate.html 这个文章上说 zone size 的意思是每秒开辟一个新的 zone,每秒超出的部分会被拒绝
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3033 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:40 · PVG 22:40 · LAX 07:40 · JFK 10:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.