key 是可以被用户自定义的,只需要修改插件的一行代码即可完成。并没有在插件中放开是处于安全的考虑。

这里以route为例(service的使用是同样的方法),在指定的 route 上启用 limit-req 插件。

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

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

添加插件

上述配置限制了每秒请求速率为 1,大于 1 小于 3 的会被加上延时,速率超过 3 就会被拒绝:

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

当你超过,就会收到包含 503 返回码的响应头:

  1. HTTP/1.1 503 Service Temporarily Unavailable
  2. Content-Type: text/html
  3. Content-Length: 194
  4. Connection: keep-alive
  5. Server: APISIX web server
  6. <html>
  7. <head><title>503 Service Temporarily Unavailable</title></head>
  8. <center><h1>503 Service Temporarily Unavailable</h1></center>
  9. <hr><center>openresty</center>
  10. </body>

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

如何在consumer上使用

consumer上开启limit-req插件,需要与授权插件一起配合使用,这里以key-auth授权插件为例。

1、将limit-req插件绑定到consumer上

2、创建route并开启key-auth插件

  1. curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "methods": ["GET"],
  4. "uri": "/index.html",
  5. "plugins": {
  6. "key-auth": {
  7. "key": "auth-jack"
  8. }
  9. },
  10. "upstream": {
  11. "type": "roundrobin",
  12. "nodes": {
  13. "127.0.0.1:1980": 1
  14. }
  15. }
  16. }'

未超过rate + burst 的值

  1. HTTP/1.1 200 OK

当超过rate + burst 的值

说明绑在consumer上的 limit-req插件生效了

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

  1. curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "methods": ["GET"],
  4. "uri": "/index.html",
  5. "upstream": {
  6. "type": "roundrobin",
  7. "nodes": {
  8. "39.97.63.215:80": 1
  9. }
  10. }
  11. }'

移除consumer上的 limit-req 插件

  1. curl http://127.0.0.1:9080/apisix/admin/consumers -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "username": "consumer_jack",
  4. "plugins": {
  5. "key-auth": {
  6. "key": "auth-jack"
  7. }

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