# 负载均衡

负载均衡是一种用于分配网络请求负载的技术。在设计需要处理大量流量的系统时，这是一个关键的考虑因素，可以提高系统性能、可扩展性和可靠性。

Apache APISIX 支持多种 [负载均衡算法](https://docs.apiseven.com/apisix/key-concepts/upstreams.md#load-balancing)，其中之一是加权轮询算法。该算法以循环模式在一组服务器上分配传入请求。

在本教程中，你将创建一个具有两个上游服务的路由，并使用轮询负载均衡算法来对请求进行负载均衡。

## 前置条件[​](#前置条件 "前置条件的直接链接")

1. 完成 [安装 APISIX](https://docs.apiseven.com/apisix/getting-started.md) 以在 Docker 中安装 APISIX。
2. 了解 APISIX [路由](https://docs.apiseven.com/apisix/key-concepts/routes.md) 和 [上游](https://docs.apiseven.com/apisix/key-concepts/upstreams.md)。
3. 如果使用这些工具，请安装 [ADC](https://docs.apiseven.com/apisix/reference/adc.md) 或 [APISIX-MCP](https://docs.apiseven.com/apisix/reference/apisix-mcp.md)。

## 启用负载均衡[​](#启用负载均衡 "启用负载均衡的直接链接")

* Admin API
* ADC
* APISIX-MCP

创建一个包含两个上游服务的路由，[httpbin.org](https://httpbin.org/headers) 和 [mock.api7.ai](https://mock.api7.ai/headers)，以在它们之间分配请求。当在 `/headers` 接收到请求时，两个服务都会响应请求头：

```
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"

  }

}'
```

❶ `type`: 使用 `roundrobin`（轮询）作为负载均衡算法。

❷ `nodes`: 上游服务。

❸ `pass_host`: 使用 `node` 将 host 头传递给上游。

❹ `scheme`: 使用 `https` 与上游启用 TLS。

如果路由创建成功，你将收到 `HTTP/1.1 201 Created` 响应。

创建一个包含指向两个上游服务 [httpbin.org](https://httpbin.org/headers) 和 [mock.api7.ai](https://mock.api7.ai/headers) 的路由的 ADC 配置文件。当在 `/headers` 接收到请求时，两个服务都会响应请求头。

adc.yaml

```
services:

  - name: headers Service

    routes:

      - uris:

          - /headers

        name: getting-started-headers

    upstream:

      type: roundrobin

      nodes:

        - host: mock.api7.ai

          port: 443

          weight: 1

        - host: httpbin.org

          port: 443

          weight: 1

      pass_host: node

      scheme: https
```

❶ `type`: 使用 `roundrobin`（轮询）作为负载均衡算法。

❷ `nodes`: 上游服务。

❸ `pass_host`: 使用 `node` 将 host 头传递给上游。

❹ `scheme`: 使用 `https` 与上游启用 TLS。

预览服务变更。以下选项仅比较本教程的服务，因此其他网关资源不会受到影响：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=load-balancing
```

检查 `diff.yaml`，确认其中仅包含预期的服务和路由变更。然后使用相同范围同步已审查的配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=load-balancing
```

如果配置同步成功，你将收到类似的响应：

```
[11:25:49 AM] [ADC] › ✔  success   Sync configuration

[11:25:49 AM] [ADC] › ★  star      All is well, see you next time!
```

在你的 AI 客户端中输入以下提示：

```
Create a route with the ID `getting-started-headers` that matches requests to `/headers`, and forward them to two upstream nodes, `httpbin.org` and `mock.api7.ai`, both on port `443`. Use the `roundrobin` algorithm and the HTTPS scheme, and pass the original host of each upstream node in the request.
```

你应该看到类似的响应：

```
Successfully created route "getting-started-headers" with:



URI: /headers

Two upstream nodes:

https://httpbin.org:443

https://mock.api7.ai:443

Round-robin load balancing

Original host headers preserved (pass_host: node)

Route ID: getting-started-headers

Status: Active (1)

Created at: 1744189246 (2025-04-09 09:00:46 UTC)

The route is now ready to distribute requests between the two upstream endpoints while maintaining the original host headers.
```

## 验证[​](#验证 "验证的直接链接")

* Admin API
* ADC
* APISIX-MCP

生成 50 个连续请求到 APISIX `/headers` 路由，以查看负载均衡效果：

```
resp=$(seq 50 | xargs -I{} curl "http://127.0.0.1:9080/headers" -sL) && \

  count_httpbin=$(echo "$resp" | grep "httpbin.org" | wc -l) && \

  count_mockapi7=$(echo "$resp" | grep "mock.api7.ai" | wc -l) && \

  echo httpbin.org: $count_httpbin, mock.api7.ai: $count_mockapi7
```

该命令分别统计了两个服务处理的请求数。输出显示请求已分发到两个服务：

```
httpbin.org: 23, mock.api7.ai: 27
```

生成 50 个连续请求到 APISIX `/headers` 路由，以查看负载均衡效果：

```
resp=$(seq 50 | xargs -I{} curl "http://127.0.0.1:9080/headers" -sL) && \

  count_httpbin=$(echo "$resp" | grep "httpbin.org" | wc -l) && \

  count_mockapi7=$(echo "$resp" | grep "mock.api7.ai" | wc -l) && \

  echo httpbin.org: $count_httpbin, mock.api7.ai: $count_mockapi7
```

该命令分别统计了两个服务处理的请求数。输出显示请求已分发到两个服务：

```
httpbin.org: 23, mock.api7.ai: 27
```

在你的 AI 客户端中输入以下提示：

```
Generate 50 consecutive requests to the APISIX /headers route to observe the load-balancing behavior, then count how many responses came from httpbin.org and how many came from mock.api7.ai.
```

你应该看到类似的响应：

```
Load balancing test results for 50 requests to /headers route:



httpbin.org responses: 23 (46%)

mock.api7.ai responses: 27 (54%)

The round-robin load balancing is working as expected, distributing requests between the two upstream nodes. The slight imbalance (46/54 split) could be due to connection timing or other network factors, but overall demonstrates effective load distribution.
```

请求在服务之间的分布应接近 1:1，但可能并不总是完全为 1:1。轻微的偏差是由于 APISIX 使用多个 worker 运行所致。

## 下一步[​](#下一步 "下一步的直接链接")

继续学习[密钥认证](https://docs.apiseven.com/apisix/getting-started/key-authentication.md)，为路由提供安全保护。
