HTTP 方法匹配
原文:https://gateway-api.sigs.k8s.io/guides/user-guides/http-method-matching/
HTTPRoute 资源 可以基于 HTTP 方法对请求进行匹配。本指南展示如何使用该功能。
基于 HTTP 方法匹配请求
下面这条 HTTPRoute 会根据请求的 HTTP 方法把流量分配到两个后端:
yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: method-matching
namespace: gateway-conformance-infra
spec:
parentRefs:
- name: same-namespace
rules:
- matches:
- method: POST
backendRefs:
- name: infra-backend-v1
port: 8080
- matches:
- method: GET
backendRefs:
- name: infra-backend-v2
port: 8080效果:
- 对
/的 POST 请求会被路由到infra-backend-v1。 - 对
/的 GET 请求会被路由到infra-backend-v2。
与其他匹配类型组合
方法匹配可以与路径、Header 等其他匹配类型组合使用。下面的规则演示了这种组合:
yaml
# 与核心匹配类型组合。
- matches:
- path:
type: PathPrefix
value: /path1
method: GET
backendRefs:
- name: infra-backend-v1
port: 8080
- matches:
- headers:
- name: version
value: one
method: PUT
backendRefs:
- name: infra-backend-v2
port: 8080
- matches:
- path:
type: PathPrefix
value: /path2
headers:
- name: version
value: two
method: POST
backendRefs:
- name: infra-backend-v3
port: 8080多个 matches 之间的"或"语义
如果一条规则有多个 matches,只要请求满足其中任意一个,就会被路由到对应的后端。下面的规则会在以下任一条件成立时把流量路由到 infra-backend-v1:
- 请求是对
/path3的 PATCH; - 或 请求是对
/path4的 DELETE,且 Header 包含version: three。
其逻辑表达式为:(cond1 AND cond2) OR (cond3 AND cond4 AND cond5)。
yaml
# 形式为 (cond1 AND cond2) OR (cond3 AND cond4 AND cond5) 的匹配
- matches:
- path:
type: PathPrefix
value: /path3
method: PATCH
- path:
type: PathPrefix
value: /path4
headers:
- name: version
value: three
method: DELETE
backendRefs:
- name: infra-backend-v1
port: 8080