limit-conn
属性
以下示例展示了如何在指定路由上启用 limit-conn
插件,并设置 key_type
为 "var"
:
你也可以设置 key_type
为 "var_combination"
:
curl http://127.0.0.1:9180/apisix/admin/routes/1 \
-H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"methods": ["GET"],
"uri": "/index.html",
"id": 1,
"plugins": {
"limit-conn": {
"burst": 0,
"default_conn_delay": 0.1,
"rejected_code": 503,
"key_type": "var_combination",
"key": "$consumer_name $remote_addr"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:1980": 1
}
}'
测试插件
curl -i http://127.0.0.1:9080/index.html?sleep=20 &
curl -i http://127.0.0.1:9080/index.html?sleep=20
Apache APISIX 支持 WebSocket 代理,我们可以使用 limit-conn
插件限制 WebSocket 连接的并发数。
1、创建路由并启用 WebSocket 代理和 limit-conn
插件。
curl http://127.0.0.1:9180/apisix/admin/routes/1 \
-H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"uri": "/ws",
"enable_websocket": true,
"plugins": {
"limit-conn": {
"conn": 1,
"burst": 0,
"default_conn_delay": 0.1,
"rejected_code": 503,
"key_type": "var",
"key": "remote_addr"
}
},
"upstream": {
"nodes": {
"127.0.0.1:1980": 1
}
}
}'
2、发起 WebSocket 请求,返回 101
HTTP 状态码表示连接建立成功。
curl --include \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==" \
--header "Sec-WebSocket-Version: 13" \
--http1.1 \
http://127.0.0.1:9080/ws
3、在另一个终端中再次发起 WebSocket 请求,返回 503
HTTP 状态码表示请求将被拒绝。
HTTP/1.1 503 Service Temporarily Unavailable
···
<html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body>
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>openresty</center>
</body>
</html>
禁用插件
curl http://127.0.0.1:9180/apisix/admin/routes/1 \
-H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"methods": ["GET"],
"uri": "/index.html",
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:1980": 1
}
}'