DiscoveryClient 路由定义定位器
DiscoveryClient Route Definition Locator
你可以配置网关,使其基于注册到兼容 DiscoveryClient 的服务注册中心的服务来创建路由。
默认情况下,创建的路由使用协议 lb://service-name(其中 service-name 是 DiscoveryClient::getServices 将返回的字符串),这意味着它们是负载均衡的。因此,你还需要包含 org.springframework.cloud:spring-cloud-starter-loadbalancer 依赖项,以便它在类路径上可用。
要启用此功能,请设置 spring.cloud.gateway.discovery.locator.enabled=true,并确保类路径上存在并启用了 DiscoveryClient 实现(例如 Netflix Eureka、Consul、Zookeeper 或 Kubernetes)。
为 DiscoveryClient 路由配置谓词和过滤器
默认情况下,网关为通过 DiscoveryClient 创建的路由定义了一个谓词和一个过滤器。
默认的谓词是一个路径谓词,其模式定义为 /serviceId/**,其中 serviceId 是来自 DiscoveryClient 的服务 ID。
默认过滤器是一个重写路径过滤器,其正则表达式为 /serviceId/?(?<remaining>.*),替换表达式为 /${remaining}。这会在请求发送到下游之前,从路径中移除服务ID。
如果你想自定义 DiscoveryClient 路由使用的断言或过滤器,请设置 spring.cloud.gateway.discovery.locator.predicates[x] 和 spring.cloud.gateway.discovery.locator.filters[y]。这样做时,如果你希望保留该功能,需要确保包含前面展示的默认断言和过滤器。以下示例展示了在 properties 和 yaml 格式中的配置方式:
示例 1. application.properties
spring.cloud.gateway.discovery.locator.predicates[0].name=Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]="'/'+serviceId+'/**'"
spring.cloud.gateway.discovery.locator.predicates[1].name=Host
spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]="'**.foo.com'"
spring.cloud.gateway.discovery.locator.filters[0].name=CircuitBreaker
spring.cloud.gateway.discovery.locator.filters[0].args[name]=serviceId
spring.cloud.gateway.discovery.locator.filters[1].name=RewritePath
spring.cloud.gateway.discovery.locator.filters[1].args[regexp]="'/' + serviceId + '/?(?<remaining>.*)'"
spring.cloud.gateway.discovery.locator.filters[1].args[replacement]="'/$\{remaining}'"
示例 2. application.yml
spring:
cloud:
gateway:
discovery:
locator:
predicates:
- name: Host
args:
pattern: "'**.foo.com'"
- name: Path
args:
pattern: "'/'+serviceId+'/**'"
filters:
- name: CircuitBreaker
args:
name: serviceId
- name: RewritePath
args:
regexp: "'/' + serviceId + '/?(?<remaining>.*)'"
replacement: "'/${remaining}'"