1 Star 0 Fork 166

wulugeng / apisix

forked from iresty / Apache APISIX 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
limit-count-cn.md 2.91 KB
一键复制 编辑 原始数据 按行查看 历史

English

limit-count

GitHub API 的限速类似, 在指定的时间范围内,限制总的请求个数。并且在 HTTP 响应头中返回剩余可以请求的个数。

参数

  • count:指定时间窗口内的请求数量阈值
  • time_window:时间窗口的大小(以秒为单位),超过这个时间就会重置
  • rejected_code:当请求超过阈值被拒绝时,返回的 HTTP 状态码,默认是 503
  • key:是用来做请求计数的依据,当前接受的 key 有:"remote_addr"(客户端IP地址), "server_addr"(服务端 IP 地址), 请求头中的"X-Forwarded-For" 或 "X-Real-IP"。

示例

开启插件

下面是一个示例,在指定的 route 上开启了 limit count 插件:

curl -i http://127.0.0.1:9080/apisix/admin/routes/1 -X PUT -d '
{
    "uri": "/index.html",
    "plugins": {
        "limit-count": {
            "count": 2,
            "time_window": 60,
            "rejected_code": 503,
            "key": "remote_addr"
        }
    },
    "upstream": {
        "type": "roundrobin",
        "nodes": {
            "39.97.63.215:80": 1
        }
    }
}'

你可以使用浏览器打开 dashboard:http://127.0.0.1:9080/apisix/dashboard,通过 web 界面来完成上面的操作,先增加一个 route:

然后在 route 页面中添加 limit-count 插件:

测试插件

上述配置限制了 60 秒内只能访问 2 次,前两次访问都会正常访问:

curl -i http://127.0.0.1:9080/index.html

响应头里面包含了 X-RateLimit-LimitX-RateLimit-Remaining,他们的含义分别是限制的总请求数和剩余还可以发送的请求数:

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 13175
Connection: keep-alive
X-RateLimit-Limit: 2
X-RateLimit-Remaining: 0
Server: APISIX web server

当你第三次访问的时候,就会收到包含 503 返回码的响应头:

HTTP/1.1 503 Service Temporarily Unavailable
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Server: APISIX web server

<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body>
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>openresty</center>
</body>
</html>

这就表示 limit count 插件生效了。

移除插件

当你想去掉 limit count 插件的时候,很简单,在插件的配置中把对应的 json 配置删除即可,无须重启服务,即刻生效:

curl http://127.0.0.1:9080/apisix/admin/routes/1 -X PUT -d '
{
    "methods": ["GET"],
    "uri": "/index.html",
    "upstream": {
        "type": "roundrobin",
        "nodes": {
            "39.97.63.215:80": 1
        }
    }
}'

现在就已经移除了 limit count 插件了。其他插件的开启和移除也是同样的方法。

Lua
1
https://gitee.com/wulugeng/apisix.git
git@gitee.com:wulugeng/apisix.git
wulugeng
apisix
apisix
master

搜索帮助