我正在将 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/