首页 > 解决方案 > 使用尤里卡的 Spring Cloud Gateway 自动路由

问题描述

我使用 Spring 来创建微服务。我使用 Eureka 进行服务发现,使用 Spring 云网关进行路由。我想自动路由我拥有的服务数量。

例如,如果一个服务“eureka-client”注册到 Eureka,并且为了使用 Spring Cloud Gateway 进行路由,我必须自己为每个服务创建一个路由,如下所示。

  routes:
  - id: eureka-client
    uri: lb://eureka-client
    predicates:
    - Path=/eureka-client/**

有一些服务是可以接受的,但我最终可能会得到数百种服务。每个都必须在 Spring Cloud Gateway 中编写自己的路由。我使用了 spring.cloud.gateway.discovery.locator.enabled=true 并没有解决问题。基本上我试图消除 yaml 文件中的路由配置。

有没有办法提供从 Spring Cloud Gateway 到 Eureka 的每个服务的自动路由?

参考:https ://cloud.spring.io/spring-cloud-gateway/reference/html/#discoveryclient-route-definition-locator

我得到 404,因为它无法获得正确的路由任何帮助将不胜感激。谢谢。

标签: javaspring-bootnetflix-eurekaspring-cloud-gateway

解决方案


自动路由配置在:

https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#the-discoveryclient-route-definition-locator

对于 Eureka Netflix 客户端,必须在 中添加所需的依赖项pom.xml,必须在主应用程序类(@EnableEurekaClient)中启用它,并且必须在中指定所需的属性applications.yml

eureka:
    client:
        fetchRegistry: true
        registerWithEureka: false
        serviceUrl:
            defaultZone: http://localhost:port/eureka
    instance:
        preferIpAddress: true

为了使用小写服务启用网关,请添加:

spring:
    application:
        name: gateway service
    cloud:
        gateway:
            discovery:
                locator:
                    enabled: 'true'
                    lower-case-service-id: 'true'

推荐阅读