如何使用服务发现来重写Spring Cloud Gateway的serviceId

我正在将zuul网关迁移到SCG。我的服务在kubernetes中运行并通过领事注册。 典型的服务名称是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

Previos 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
evilyue 回答:如何使用服务发现来重写Spring Cloud Gateway的serviceId

我的位置完全一样。您找到解决这个问题的诀窍了吗? 我知道我们可以像这样在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

但是获得一个不太脏的解决方案可能很棒。

本文链接:https://www.f2er.com/3138807.html

大家都在问