高级路由
Envoy 提供强大的路由功能,支持复杂的路由规则和高级特性。
优先级路由
路由优先级配置
route_config:
virtual_hosts:
- name: example_vhost
domains: ["*"]
routes:
- match:
prefix: "/api/v2"
route:
cluster: api_v2
priority: HIGH
- match:
prefix: "/api"
route:
cluster: api_v1
priority: DEFAULT
优先级特性
- HIGH:高优先级,具有独立的连接池和熔断器设置
- DEFAULT:默认优先级
- 每个优先级有独立的连接池配置
虚拟集群
虚拟集群用于为特定端点生成统计信息。
虚拟集群配置
route_config:
virtual_hosts:
- name: example_vhost
domains: ["*"]
virtual_clusters:
- name: "api_stats"
pattern: "^/api/.*$"
method: GET
- name: "user_stats"
pattern: "^/users/\\d+$"
method: POST
routes:
- match:
prefix: "/api"
route:
cluster: api_service
复杂路由规则
组合匹配条件
routes:
- match:
prefix: "/api"
headers:
- name: "x-version"
string_match:
exact: "v2"
- name: "x-client"
string_match:
prefix: "mobile"
query_parameters:
- name: "debug"
string_match:
exact: "true"
route:
cluster: api_v2_debug
正则表达式路由
routes:
- match:
safe_regex:
google_re2: {}
regex: "^/users/(\\d+)/profile$"
route:
cluster: user_profile_service
regex_rewrite:
pattern:
google_re2: {}
regex: "^/users/(\\d+)/profile$"
substitution: "/profile/\\1"
路由重写
路径重写
routes:
- match:
prefix: "/api/v1"
route:
cluster: api_service
prefix_rewrite: "/api"
host_rewrite_literal: "api.example.com"
正则重写
routes:
- match:
safe_regex:
google_regex: {}
regex: "^/service/([^/]+)/(.*)$"
route:
cluster: dynamic_service
regex_rewrite:
pattern:
google_regex: {}
regex: "^/service/([^/]+)/(.*)$"
substitution: "/\\2"
路由元数据
路由级别元数据
routes:
- match:
prefix: "/api"
route:
cluster: api_service
metadata:
filter_metadata:
envoy.filters.http.ratelimit:
rate_limit_key: "api"
envoy.filters.http.cors:
allow_origin: "*"
虚拟主机元数据
virtual_hosts:
- name: example_vhost
domains: ["*"]
metadata:
filter_metadata:
envoy.filters.http.ratelimit:
rate_limit_key: "vhost"
routes:
- match:
prefix: "/"
route:
cluster: default_service
路由统计
自定义统计名称
routes:
- match:
prefix: "/api"
route:
cluster: api_service
stat_name: "api_requests"
虚拟集群统计
virtual_clusters:
- name: "api_stats"
pattern: "^/api/.*$"
method: GET
stat_name: "api_get_requests"
路由超时和重试
路由级别超时
routes:
- match:
prefix: "/slow-api"
route:
cluster: slow_service
timeout: 30s
retry_policy:
retry_on: "5xx,connect-failure"
num_retries: 3
per_try_timeout: 10s
虚拟主机级别超时
virtual_hosts:
- name: example_vhost
domains: ["*"]
routes:
- match:
prefix: "/"
route:
cluster: default_service
timeout: 15s
retry_policy:
retry_on: "5xx"
num_retries: 2
路由缓存
路由缓存配置
route_config:
name: cached_route
virtual_hosts:
- name: example_vhost
domains: ["*"]
routes:
- match:
prefix: "/cache"
route:
cluster: cache_service
request_mirror_policies:
- cluster: cache_warmup
runtime_fraction:
default_value:
numerator: 10
denominator: HUNDRED
最佳实践
1. 路由设计
- 使用明确的匹配规则
- 合理设置路由优先级
- 避免过于复杂的路由规则
- 使用虚拟集群进行统计
2. 性能优化
- 合理使用路由缓存
- 优化正则表达式性能
- 监控路由匹配性能
- 使用适当的超时设置
3. 监控和调试
- 监控路由统计信息
- 记录路由匹配日志
- 设置路由告警
- 定期审查路由规则
注意事项
- 复杂的路由规则可能影响性能
- 正则表达式需要谨慎使用
- 路由变更需要谨慎测试
- 需要确保所有流量都有匹配的路由
高级路由功能为 Envoy 提供了强大的流量控制能力,合理使用可以实现复杂的业务需求。