limit-req
limit-req 插件使用漏桶算法来限制请求数量并允许进行流量整形。
本地限速与基于 Redis 的限速
limit-req 插件支持两种限速模式:
- 本地限速:每个网关实例独立实施限速。每个实例维护自己的计数器,因此当流量分散到多个实例时,实际限额约为“限额 × 实例数”。未设置
policy或将其设置为local时,这是默认模式。 - 基于 Redis 的限速:所有网关实例通过 Redis 共享限额,因此配置的限额会应用到所有网关实例。
示例
以下示例演示了如何在不同场景下配置 limit-req。
基于远程地址进行速率限制
以下示例演示了如何通过单个变量 remote_addr 对 HTTP 请求进行速率限制。
创建一个启用了 limit-req 插件的路由,配置为每个远程地址允许 1 QPS:
- Admin API
- ADC
- Ingress Controller
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '
{
"id": "limit-req-route",
"uri": "/get",
"plugins": {
"limit-req": {
"rate": 1,
"burst": 0,
"key": "remote_addr",
"key_type": "var",
"rejected_code": 429,
"policy": "local",
"nodelay": true
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
adc.yaml
services:
- name: httpbin
routes:
- uris:
- /get
name: limit-req-route
plugins:
limit-req:
rate: 1
burst: 0
key: remote_addr
key_type: var
rejected_code: 429
policy: local
nodelay: true
upstream:
type: roundrobin
nodes:
- host: httpbin.org
port: 80
weight: 1
将配置同步到网关:
adc sync -f adc.yaml
- Gateway API
- APISIX CRD
limit-req-ic.yaml
apiVersion: v1
kind: Service
metadata:
namespace: aic
name: httpbin-external-domain
spec:
type: ExternalName
externalName: httpbin.org
---
apiVersion: apisix.apache.org/v1alpha1
kind: PluginConfig
metadata:
namespace: aic
name: limit-req-plugin-config
spec:
plugins:
- name: limit-req
config:
rate: 1
burst: 0
key: remote_addr
key_type: var
rejected_code: 429
policy: local
nodelay: true
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: limit-req-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /get
filters:
- type: ExtensionRef
extensionRef:
group: apisix.apache.org
kind: PluginConfig
name: limit-req-plugin-config
backendRefs:
- name: httpbin-external-domain
port: 80
limit-req-ic.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixUpstream
metadata:
namespace: aic
name: httpbin-external-domain
spec:
ingressClassName: apisix
externalNodes:
- type: Domain
name: httpbin.org
---
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: limit-req-route
spec:
ingressClassName: apisix
http:
- name: limit-req-route
match:
paths:
- /get
methods:
- GET
upstreams:
- name: httpbin-external-domain
plugins:
- name: limit-req
config:
rate: 1
burst: 0
key: remote_addr
key_type: var
rejected_code: 429
policy: local
nodelay: true
应用配置:
kubectl apply -f limit-req-ic.yaml
❶ rate:将 QPS 限制为 1。
❷ key:设置为 remote_addr,以根据远程地址应用速率限制配额。
❸ key_type:设置为 var,以将 key 解释为变量。
发送请求进行验证:
curl -i "http://127.0.0.1:9080/get"
你应该会看到一个 HTTP/1.1 200 OK 响应。
该请求已消耗了时间窗口内允许的所有配额。如果你在同一秒内再次发送请求,应该会收到一个 HTTP/1.1 429 Too Many Requests 响应,表明请求超过了配额阈值。