启用负载均衡
创建一个具有两个上游服务的路由,访问 /headers 将被转发到 httpbin.org 和 mock.api7.ai 这两个上游服务,并且会返回请求头。
curl -i "http://127.0.0.1:9180/apisix/admin/routes" -X PUT -d '
{
"id": "getting-started-headers",
"uri": "/headers",
"upstream" : {
"type": "roundrobin",
"nodes": {
"httpbin.org:443": 1,
"mock.api7.ai:443": 1
},
"pass_host": "node",
"scheme": "https"
}
}'
创建返回结果:
HTTP/1.1 201 Created
Date: Sun, 28 Jan 2024 11:56:02 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Server: APISIX/3.8.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: *
Access-Control-Max-Age: 3600
X-API-VERSION: v3
{"key":"/apisix/routes/getting-started-headers","value":{"id":"getting-started-headers","create_time":1706442962,"priority":0,"upstream":{"scheme":"https","nodes":{"httpbin.org:443":1,"mock.api7.ai:443":1},"type":"roundrobin","pass_host":"node","hash_on":"vars"},"uri":"/headers","status":1,"update_time":1706442962}}
验证这两个服务返回不同的数据。
生成 100 个请求来测试负载均衡的效果:
hc=$(seq 100 | xargs -I {} curl "http://127.0.0.1:9080/headers" -sL | grep "httpbin" | wc -l); echo httpbin.org: $hc, mock.api7.ai: $((100 - $hc))
验证返回:
httpbin.org: 54, mock.api7.ai: 46