java - 如何通过服务发现重写 Spring Cloud Gateway 的 serviceId

标签 java spring-cloud-gateway

我正在将 zuul 网关迁移到 SCG。我的服务在 kubernetes 中运行并通过 consul 注册。 典型的服务名称是 xxx-service。因此,使用当前的网关配置,我可以通过 http://address/api/xxx-service/some-path 来调用它们

我当前的配置:

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          predicates:
            - name: Path
              args:
                pattern: "'/api/' + serviceId + '/**'"
          filters:
            - name: RewritePath
              args:
                regexp: "'/api/' + serviceId + '/(?<remaining>.*)'"
                replacement: "'/${remaining}'"

但是客户端在调用它们时不应在服务名称中添加“-service”后缀。如何配置 SCG 以便能够通过以下方式调用服务 http://address/api/xxx-service/some-path

之前的zuul配置:

zuul.routes.xxx.service-id=xxx-service
zuul.routes.aaa-bbb.service-id=aaa-bbb-service
zuul.routes.aaa-bbb.path=/aaa/bbb/**
zuul.strip-prefix=true
zuul.prefix=/api

最佳答案

我的处境完全相同。你找到解决这个问题的窍门了吗? 我知道我们可以在 RouteLocator 中定义所有路由,如下所示:

/**
 * Route constructions.
 *
 * @param builder
 *                the builder instance
 * @return the final route locator
 */
@Bean
public RouteLocator gatewayRoutes(final RouteLocatorBuilder builder) {
return builder.routes()
    // Declare First service
    .route(r -> r.path("/prefix/myservice1-service/**")
        .filters(f -> f.rewritePath("/prefix/myservicename1-service/(?<remaining>.*)", "/${remaining}"))
        .uri("lb://myservice1").id("myservice1"))

    // Declare Second service
    .route(r -> r.path("/prefix/myservice2-service/**")
        .filters(f -> f.rewritePath("/prefix/myservicename2-service/(?<remaining>.*)", "/${remaining}"))
        .uri("lb://myservice2").id("myservice2"))

    // Etc... Then build
    .build();
}

我不确定,但也许您需要禁用发现定位器才能正确执行此操作。

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: false

但如果能找到一个不那么脏的解决方案就太好了。

关于java - 如何通过服务发现重写 Spring Cloud Gateway 的 serviceId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58764503/

相关文章:

java - Android - 应用程序仅在第一次启动时崩溃,但第二次运行

java - com.google.inject 包可从多个模块访问

spring-cloud - 实例关闭时的 Spring Cloud Gateway 500

spring cloud gateway异常索引错误的权限中存在非法字符

java - 错误:不兼容的类型:org.opencv.core.Point无法转换为android.graphics.Point

java - 如何使用循环一一获取枚举值

spring-boot - Spring Cloud Gateway 找不到 Fluent Java Routes API

spring-boot - Spring云网关中如何添加Pre Filter

java - 如何 "remove the gobal prefix('/api') 然后转到 lb ://"when migrate to spring cloud gateway from zuul

java - 在 Box2D (libgdx) 中移除主体会立即导致游戏崩溃