# Traffic Label

`traffic-label` 插件对请求表达式求值，并从首个能产生动作的匹配规则中按权重选择动作。当前版本支持在请求转发到上游前添加或替换请求头。

## 示例[​](#示例 "示例的直�接链接")

以下示例展示了如何在不同场景下的路由上配置 `traffic-label`。

### 定义单个匹配条件[​](#定义单个匹配条件 "定义单个匹配条件的直接链接")

以下示例展示了一个包含一个匹配条件和一个关联动作的简单规则。如果请求的 URI 为 `/headers`，插件将向请求添加头 `"X-Server-Id": "100"`。

* 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": "traffic-label-route",

    "uri":"/headers",

    "plugins":{

      "traffic-label": {

        "rules": [

          {

            "match": [

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

            ],

            "actions": [

              {

                "set_headers": {

                  "X-Server-Id": 100

                }

              }

            ]

          }

        ]

      }

    },

    "upstream":{

      "type":"roundrobin",

      "nodes":{

        "httpbin.org:80":1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /headers

        name: traffic-label-route

        plugins:

          traffic-label:

            rules:

              - match:

                  - - uri

                    - "=="

                    - /headers

                actions:

                  - set_headers:

                      X-Server-Id: 100

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

traffic-label-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: traffic-label-plugin-config

spec:

  plugins:

    - name: traffic-label

      config:

        rules:

          - match:

              - - uri

                - "=="

                - /headers

            actions:

              - set_headers:

                  X-Server-Id: 100

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: traffic-label-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /headers

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: traffic-label-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

traffic-label-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: traffic-label-route

spec:

  ingressClassName: apisix

  http:

    - name: traffic-label-route

      match:

        paths:

          - /headers

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: traffic-label

          config:

            rules:

              - match:

                  - - uri

                    - "=="

                    - /headers

                actions:

                  - set_headers:

                      X-Server-Id: 100
```

应用配置：

```
kubectl apply -f traffic-label-ic.yaml
```

发送请求进行验证：

```
curl "http://127.0.0.1:9080/headers"
```

你应该看到类似于以下的响应：

```
{

  "headers": {

    "Accept": "*/*",

    ...

    "X-Server-Id": "100"

  }

}
```

### 定义带有逻辑运算符的多个匹配条件[​](#定义带有逻辑运算符的多个匹配条件 "定义带有逻辑运算符的多个匹配条件的直接链接")

你可以使用[逻辑运算符](https://docs.apiseven.com/apisix/reference/apisix-expressions.md#logical-operators)构建更复杂的匹配条件。

以下示例展示了一个规则，包含两个通过 `OR` 逻辑分组的匹配条件和一个关联动作。如果满足其中任何一个条件，插件将向请求添加头 `"X-Server-Id": "100"`。

* 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": "traffic-label-route",

    "uri":"/headers",

    "plugins":{

      "traffic-label": {

        "rules": [

          {

            "match": [

              "OR",

              ["arg_version", "==", "v1"],

              ["arg_env", "==", "dev"]

            ],

            "actions": [

              {

                "set_headers": {

                  "X-Server-Id": 100

                }

              }

            ]

          }

        ]

      }

    },

    "upstream":{

      "type":"roundrobin",

      "nodes":{

        "httpbin.org:80":1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /headers

        name: traffic-label-route

        plugins:

          traffic-label:

            rules:

              - match:

                  - OR

                  - - arg_version

                    - "=="

                    - v1

                  - - arg_env

                    - "=="

                    - dev

                actions:

                  - set_headers:

                      X-Server-Id: 100

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

traffic-label-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: traffic-label-plugin-config

spec:

  plugins:

    - name: traffic-label

      config:

        rules:

          - match:

              - OR

              - - arg_version

                - "=="

                - v1

              - - arg_env

                - "=="

                - dev

            actions:

              - set_headers:

                  X-Server-Id: 100

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: traffic-label-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /headers

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: traffic-label-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

traffic-label-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: traffic-label-route

spec:

  ingressClassName: apisix

  http:

    - name: traffic-label-route

      match:

        paths:

          - /headers

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: traffic-label

          config:

            rules:

              - match:

                  - OR

                  - - arg_version

                    - "=="

                    - v1

                  - - arg_env

                    - "=="

                    - dev

                actions:

                  - set_headers:

                      X-Server-Id: 100
```

应用配置：

```
kubectl apply -f traffic-label-ic.yaml
```

发送请求进行验证：

```
curl "http://127.0.0.1:9080/headers?env=dev"
```

你应该看到类似于以下的响应：

```
{

  "headers": {

    "Accept": "*/*",

    ...

    "X-Server-Id": "100"

  }

}
```

如果你发送一个不匹配任何条件的请求，你将不会看到 `"X-Server-Id": "100"` 被添加到请求头中。

### 创建加权动作[​](#创建加权动作 "创建加权动作的直接链接")

以下示例展示了一个包含一个匹配条件和多个加权动作的规则，进入的请求将根据权重比例进行分配。

如果某个 `weight` 没有关联任何动作，则这部分请求将不会执行任何动作。

* 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": "traffic-label-route",

    "uri":"/headers",

    "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

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /headers

        name: traffic-label-route

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

预览变更，确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

traffic-label-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: traffic-label-plugin-config

spec:

  plugins:

    - name: traffic-label

      config:

        rules:

          - match:

              - - uri

                - "=="

                - /headers

            actions:

              - set_headers:

                  X-Server-Id: 100

                weight: 3

              - set_headers:

                  X-API-Version: v2

                weight: 2

              - weight: 5

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: traffic-label-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /headers

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: traffic-label-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

traffic-label-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: traffic-label-route

spec:

  ingressClassName: apisix

  http:

    - name: traffic-label-route

      match:

        paths:

          - /headers

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: traffic-label

          config:

            rules:

              - match:

                  - - uri

                    - "=="

                    - /headers

                actions:

                  - set_headers:

                      X-Server-Id: 100

                    weight: 3

                  - set_headers:

                      X-API-Version: v2

                    weight: 2

                  - weight: 5
```

应用配置：

```
kubectl apply -f traffic-label-ic.yaml
```

每个动作执行的比例取决于该动作的权重相对于 `actions` 字段下列出的所有动作总权重的比例。这里，总权重计算为所有动作权重的总和：3 + 2 + 5 = 10。

因此：

❶ 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 -i "X-Server-Id" | wc -l) && \

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

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

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

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

### 定义多个匹配规则[​](#定义多个匹配规则 "定义多个匹配规则的直接链接")

以下示例展示了使用多个规则，每个规则都有自己的匹配条件和动作。

* 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": "traffic-label-route",

    "uri":"/headers",

    "plugins":{

      "traffic-label": {

        "rules": [

          {

            "match": [

              ["arg_version", "==", "v1"]

            ],

            "actions": [

              {

                "set_headers": {

                  "X-Server-Id": 100

                }

              }

            ]

          },

          {

            "match": [

              ["arg_version", "==", "v2"]

            ],

            "actions": [

              {

                "set_headers": {

                  "X-Server-Id": 200

                }

              }

            ]

          }

        ]

      }

    },

    "upstream":{

      "type":"roundrobin",

      "nodes":{

        "httpbin.org:80":1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: httpbin

    routes:

      - uris:

          - /headers

        name: traffic-label-route

        plugins:

          traffic-label:

            rules:

              - match:

                  - - arg_version

                    - "=="

                    - v1

                actions:

                  - set_headers:

                      X-Server-Id: 100

              - match:

                  - - arg_version

                    - "=="

                    - v2

                actions:

                  - set_headers:

                      X-Server-Id: 200

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，确认仅影响本指南的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

traffic-label-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: traffic-label-plugin-config

spec:

  plugins:

    - name: traffic-label

      config:

        rules:

          - match:

              - - arg_version

                - "=="

                - v1

            actions:

              - set_headers:

                  X-Server-Id: 100

          - match:

              - - arg_version

                - "=="

                - v2

            actions:

              - set_headers:

                  X-Server-Id: 200

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: traffic-label-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /headers

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: traffic-label-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

traffic-label-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: traffic-label-route

spec:

  ingressClassName: apisix

  http:

    - name: traffic-label-route

      match:

        paths:

          - /headers

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: traffic-label

          config:

            rules:

              - match:

                  - - arg_version

                    - "=="

                    - v1

                actions:

                  - set_headers:

                      X-Server-Id: 100

              - match:

                  - - arg_version

                    - "=="

                    - v2

                actions:

                  - set_headers:

                      X-Server-Id: 200
```

应用配置：

```
kubectl apply -f traffic-label-ic.yaml
```

发送请求到 `/headers?version=v1` 进行验证：

```
curl "http://127.0.0.1:9080/headers?version=v1"
```

你应该看到类似于以下的响应：

```
{

  "headers": {

    "Accept": "*/*",

    ...

    "X-Server-Id": "100"

  }

}
```

发送请求到 `/headers?version=v2` 进行验证：

```
curl "http://127.0.0.1:9080/headers?version=v2"
```

你应该看到类似于以下的响应：

```
{

  "headers": {

    "Accept": "*/*",

    ...

    "X-Server-Id": "200"

  }

}
```
