# 条件流量管理

条件流量管理是指根据每个请求的某些特征（例如请求标头、URI 参数或 URI 路径）执行特定操作的能力。这使得人们能够实施动态和灵活的路由、限流限速或其他操作，从而允许根据应用程序或系统的特定需求对网关的行为进行细粒度控制和自定义。

本指南将向你展示如何使用 [`traffic-split`](https://docs.apiseven.com/hub/traffic-split.md)、[`traffic-label`](https://docs.apiseven.com/hub/traffic-label.md) 和 [`workflow`](https://docs.apiseven.com/hub/workflow.md) 插件在 APISIX 中有条件地管理流量。

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

* 安装 [Docker](https://docs.docker.com/get-docker)。
* 安装 [cURL](https://curl.se/) 以向服务发送请求进行验证。
* 按照 [快速入门教程](https://docs.apiseven.com/apisix/getting-started.md) 在 Docker 或 Kubernetes 中启动一个新的 APISIX 实例。

## 按条件和比例转发流量[​](#按条件和比例转发流量 "按条件和比例转发流量的直接链接")

在本节中，你将了解如何使用 `traffic-split` 插件按条件和权重将流量转发到不同的上游服务。

创建如下路由：

* Admin API
* ADC

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "uri": "/headers",

    "id": "traffic-split-route",

    "plugins": {

      "traffic-split": {

        "rules": [

          {

            "match": [

              {

                "vars": [

                  ["arg_name","==","jack"],

                  ["http_user-id",">","23"],

                  ["http_apisix-key","~~","^[a-z]+$"]

                ]

              }

            ],

            "weighted_upstreams": [

              {

                "upstream": {

                  "type": "roundrobin",

                  "scheme": "https",

                  "pass_host": "node",

                  "nodes": {

                    "httpbin.org:443":1

                  }

                },

                "weight": 3

              },

              {

                "weight": 2

              }

            ]

          }

        ]

      }

    },

    "upstream": {

      "type": "roundrobin",

      "scheme": "https",

      "pass_host": "node",

      "nodes": {

        "mock.api7.ai:443":1

      }

    }

  }'
```

❶ 仅当请求包含 URL 参数 `name=jack`、标头 `user-id` 的值大于 23 且另一个标头 `apisix-key` 的值由小写英文字母组成时，才执行插件以重定向流量。

adc.yaml

```
services:

  - name: Mock Service

    labels:

      docs-example: conditional-traffic-management

    routes:

      - uris:

          - /headers

        name: traffic-split-route

        plugins:

          traffic-split:

            rules:

              - match:

                  - vars:

                      - [arg_name, "==", "jack"]

                      - [http_user-id, ">", "23"]

                      - [http_apisix-key, "~~", "^[a-z]+$"]

                weighted_upstreams:

                  - upstream:

                      type: roundrobin

                      scheme: https

                      pass_host: node

                      nodes:

                        'httpbin.org:443': 1

                    weight: 3

                  - weight: 2

    upstream:

      type: roundrobin

      scheme: https

      pass_host: node

      nodes:

        - host: mock.api7.ai

          port: 443

          weight: 1
```

❶ 仅当请求包含 URL 参数 `name=jack`、标头 `user-id` 的值大于 23 且另一个标头 `apisix-key` 的值由小写英文字母组成时，才执行插件以重定向流量。

ADC 将服务协调为期望状态。标签选择器会将本示例限制在其自己的服务范围内。预览限定范围内的变更，并确认其中没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=conditional-traffic-management
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=conditional-traffic-management
```

如果满足条件，60% 的流量应指向 `httpbin.org`，另外 40% 应指向 `mock.api7.ai`。如果不满足条件，所有流量应指向 `mock.api7.ai`。

发送 10 个满足所有条件的连续请求以进行验证：

```
resp=$(seq 10 | xargs -I{} curl "http://127.0.0.1:9080/headers?name=jack" -H 'user-id: 30' -H 'apisix-key: helloapisix' -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: 6, mock.api7.ai: 4
```

发送两组请求进行验证：两组中的 `name` 和 `user-id` 都满足条件，但 `apisix-key` 分别包含数字或大写字母：

```
for apisix_key in hello123 HelloApisix; do

  resp=$(seq 10 | xargs -I{} curl "http://127.0.0.1:9080/headers?name=jack" -H 'user-id: 30' -H "apisix-key: ${apisix_key}" -sL)

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

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

  echo "${apisix_key}: httpbin.org: ${count_httpbin}, mock.api7.ai: ${count_mockapi7}"

done
```

由于正则表达式要求请求头的完整值只能包含小写英文字母，两组请求都应使用路由的默认上游：

```
hello123: httpbin.org: 0, mock.api7.ai: 10

HelloApisix: httpbin.org: 0, mock.api7.ai: 10
```

`traffic-split` 插件的一个常见用例是实施发布策略，例如灰度发布和蓝绿部署。有关更多插件用法，请参阅 [插件文档](https://docs.apiseven.com/hub/traffic-split.md)。

## 按条件和比例标记流量标头[​](#按条件和比例标记流量标头 "按条件和比例标记流量标头的直接链接")

在本节中，你将了解如何使用 [`traffic-label`](https://docs.apiseven.com/hub/traffic-label.md) 插件按条件和权重向请求添加请求头。

创建如下路由：

* Admin API
* ADC

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "traffic-label-route",

    "uri":"/headers",

    "priority": 10,

    "plugins":{

      "traffic-label": {

        "rules": [

          {

            "match": [

              ["uri", "==", "/headers"]

            ],

            "actions": [

              {

                "set_headers": {

                  "X-Server-Id": 100

                },

                "weight": 3

              },

              {

                "set_headers": {

                  "X-API-Version": "v2"

                },

                "weight": 2

              },

              {

                "weight": 5

              }

            ]

          }

        ]

      }

    },

    "upstream":{

      "type":"roundrobin",

      "nodes":{

        "httpbin.org:80":1

      }

    }

  }'
```

❶ 30% 的请求应具有 `X-Server-Id: 100` 请求头。

❷ 20% 的请求应具有 `X-API-Version: v2` 请求头。

❸ 50% 的请求不应对其执行任何操作。

为本示例使用独立的服务名称。ADC 按名称匹配服务，因此即使标签不同，复用 `httpbin Service` 也会更新既有服务。如果此前已同步过本示例，请在完成同步后删除 `httpbin Service` 上旧的 `traffic-label-route` 路由，并保留该服务上的其他所有路由。

adc.yaml

```
services:

  - name: Traffic Label Service

    labels:

      docs-example: conditional-traffic-label

    routes:

      - uris:

          - /headers

        name: traffic-label-route

        priority: 10

        plugins:

          traffic-label:

            rules:

              - match:

                  - [uri, "==", "/headers"]

                actions:

                  - set_headers:

                      X-Server-Id: 100

                    weight: 3

                  - set_headers:

                      X-API-Version: v2

                    weight: 2

                  - weight: 5

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 30% 的请求应具有 `X-Server-Id: 100` 请求头。

❷ 20% 的请求应具有 `X-API-Version: v2` 请求头。

❸ 50% 的请求不应对其执行任何操作。

仅预览本示例带标签的服务，并确认差异中没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=conditional-traffic-label
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=conditional-traffic-label
```

此路由的优先级为 `10`。当这条路由和前面配置的 `traffic-split-route` 都匹配 `/headers` 时，APISIX 会选择这条路由。

❶ 30% 的请求应具有 `X-Server-Id: 100` 请求头。

❷ 20% 的请求应具有 `X-API-Version: v2` 请求头。

❸ 50% 的请求不应执行任何操作。

生成 50 个连续请求以验证加权操作：

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

  count_w3=$(echo "$resp" | grep "X-Server-Id" | wc -l) && \

  count_w2=$(echo "$resp" | grep "X-API-Version" | wc -l) && \

  echo X-Server-Id: $count_w3, X-API-Version: $count_w2
```

响应显示标头以加权方式添加到请求中：

```
X-Server-Id: 15, X-API-Version: 10
```

有关更多插件用法，请参阅 [插件文档](https://docs.apiseven.com/hub/traffic-label.md)。

## 有条件地对流量进行限流限速[​](#有条件地对流量进行限流限速 "有条件地对流量进行限流限速的直接链接")

在本节中，你将了解如何使用 `workflow` 插件有条件地按计数实施限流限速。

创建如下路由：

* Admin API
* ADC

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "id": "workflow-route",

    "uri": "/anything/*",

    "plugins":{

      "workflow":{

        "rules":[

          {

            "case":[

              ["uri", "==", "/anything/rate-limit"],

              ["arg_env", "==", "v1"]

            ],

            "actions":[

              [

                "limit-count",

                {

                  "count":1,

                  "time_window":60,

                  "rejected_code":429

                }

              ]

            ]

          }

        ]

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org": 1

      }

    }

  }'
```

❶ 仅当请求的 URI 路径为 `/anything/rate-limit` 且包含 URL 参数 `env=v1` 时，才执行插件以进行限流限速。

❷ 匹配规则时应用限流限速。

为本示例使用独立的服务名称。ADC 按名称匹配服务，因此即使标签不同，复用 `httpbin Service` 也会更新既有服务。如果此前已同步过本示例，请在完成同步后删除 `httpbin Service` 上旧的 `workflow-route` 路由，并保留该服务上的其他所有路由。

adc.yaml

```
services:

  - name: Conditional Rate Limit Service

    labels:

      docs-example: conditional-rate-limit

    routes:

      - uris:

          - /anything/*

        name: workflow-route

        plugins:

          workflow:

            rules:

              - case:

                  - [uri, "==", "/anything/rate-limit"]

                  - [arg_env, "==", "v1"]

                actions:

                  - - limit-count

                    - count: 1

                      time_window: 60

                      rejected_code: 429

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 仅当请求的 URI 路径为 `/anything/rate-limit` 且包含 URL 参数 `env=v1` 时，才执行插件以进行限流限速。

❷ 匹配规则时应用限流限速。

仅预览本示例带标签的服务，并确认差异中没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=conditional-rate-limit
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=conditional-rate-limit
```

生成两个符合条件的连续请求：

```
curl -i "http://127.0.0.1:9080/anything/rate-limit?env=v1"
```

你应该收到一个 `HTTP/1.1 200 OK` 响应和一个 `HTTP 429 Too Many Requests` 响应。

生成不符合条件的请求：

```
curl -i "http://127.0.0.1:9080/anything/anything?env=v1"
```

你应该收到所有请求的 `HTTP/1.1 200 OK` 响应，因为它们没有被限流限速。

有关更多插件用法，请参阅 [插件文档](https://docs.apiseven.com/hub/workflow.md)。

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

你现在已经了解了 APISIX 支持条件流量管理的各种方式，使用 [`traffic-split`](https://docs.apiseven.com/hub/traffic-split.md)、[`traffic-label`](https://docs.apiseven.com/hub/traffic-label.md) 和 [`workflow`](https://docs.apiseven.com/hub/workflow.md) 插件。

为了满足更复杂的条件流量管理需求，请查看如何 [创建自定义插件](https://docs.apiseven.com/apisix/how-to-guide/custom-plugins/create-plugin-in-lua.md)，或使用 [无服务器函数插件](https://docs.apiseven.com/hub/serverless-functions.md) 在运行时执行自定义代码。
