【问题标题】:Spring Cloud Gateway and DiscoveryClient RoutesSpring Cloud Gateway 和 DiscoveryClient 路由
【发布时间】:2019-08-03 10:27:00
【问题描述】:

我正在尝试将使用 spring-cloud-starter-netflix-zuul 的网关迁移到 Spring Cloud Gateway,但我遇到了请求路由问题。

我遇到了以下有关为 DiscoveryClient 路由配置谓词和过滤器的文档:

Configuring Predicates and Filters For DiscoveryClient Routes

这是我的 Netflix Zuul 配置中的一个 sn-p:

zuul:
  routes:
    account-service: /accounts/**

这是来自 Spring Cloud Gateway 配置的 sn-p,我正在尝试配置等效路由:

spring:
  cloud:
    gateway:
      routes:
        - id: account-service-route
          uri: lb://account-service
          predicates:
          - Path=/accounts/**

我使用 Spring Cloud Eureka 作为我的发现服务器(在一个单独的微服务中),我目前没有Configuring Predicates and Filters For DiscoveryClient Routes 中所述的任何配置

如果我向/accounts/*** 发出请求,我会收到 404 响应。如果我将 Spring Cloud Gateway 配置更改为以下内容并向/account-service/*** 发出相同的请求,我会收到 403 Forbidden 响应:

spring:
  cloud:
    gateway:
      routes:
        - id: account-service-route
          uri: lb://account-service
          predicates:
          - Path=/account-service/**

我怀疑这与 Spring Cloud Gateway 在如何配置 DiscoveryClient 路由方面的默认行为有关,但我在日志中看不到足够的信息来为我指明正确的方向。

所以,我的问题是:当使用 Spring Cloud Gateway 和 Spring Cloud Eureka 时,是否需要按照Configuring Predicates and Filters For DiscoveryClient Routes 中所述进行配置条目?

如果是这样,有人可以参考我的路线示例就需要配置的内容提供更多解释/说明吗?抱歉,如果我遗漏了一些东西,但从我读到的这个配置到底需要什么对我来说并不明显。例如,spring.cloud.gateway.discovery.locator.predicatesspring.cloud.gateway.discovery.locator.filters 是否配置为补充或代替 spring.cloud.gateway.routes 谓词和过滤器?

如果没有,我可能缺少哪些其他配置?

我在 Spring Cloud Finchley.SR3/Spring Boot 2.0.8.RELEASE 上。

【问题讨论】:

    标签: spring-cloud-gateway


    【解决方案1】:

    设置

      cloud:
        gateway:
          discovery:
            locator:
              enabled: true  # default false
    

    会自动为Eureka上注册的EVERY服务创建路由,所以你可以通过http://<gateway>/<service-name>/path访问EVERY服务,它会重定向到lb://<service-name>/path使用负载均衡器。 当服务在 Eureka 注销时,它也会从网关中删除路由。

    此设置非常简单,适用于许多情况。请记住,默认情况下,路由将在大约 30 秒内出现/消失,您可能希望将该间隔减少到 5 秒,例如使用

    eureka:
      client:
        registry-fetch-interval-seconds: 5
    

    【讨论】:

      【解决方案2】:

      Spring Cloud Gateway 默认只启用请求路由,您必须显式启用发现支持。试试这个:

      spring:
        application:
          name: gateway
        cloud:
          gateway:
            discovery:
              locator:
                enabled: true  # default false
            routes:
              - id: account-service-route
                uri: lb://account-service #
                predicates:
                  - Path=/account/**
      

      现在你应该可以通过http://<gateway>/account-service/account/**访问你的服务了

      【讨论】:

        猜你喜欢
        • 2019-03-31
        • 2023-01-21
        • 1970-01-01
        • 1970-01-01
        • 2019-09-23
        • 2021-11-19
        • 2023-04-02
        • 2019-10-29
        • 2018-07-01
        相关资源
        最近更新 更多