DiscoveryClient 路由定義定位器

您可以配置閘道器以根據在 DiscoveryClient 相容的服務登錄檔中註冊的服務來建立路由。

預設情況下,建立的路由使用協議 lb://service-name(其中 service-nameDiscoveryClient::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]。這樣做時,如果您想保留該功能,則需要確保包含前面所示的預設謂詞和過濾器。以下示例顯示了在屬性和 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}'"
© . This site is unofficial and not affiliated with VMware.