带有路径的Spring云网关路由

问题描述 投票:0回答:1

我正在尝试编写带有路径的网关路由(将所有内容路由到www.example.com/foobar/),但“/foobar/”部分被忽略,所有内容都路由到www.example。 com/

我的 RouteLocator 配置是:

@Bean
public RouteLocator myRouteLocator(final RouteLocatorBuilder builder) {
    return builder.routes()
            .route(route -> route.path("/**").uri("http://www.example.com/foobar"))
            .build();
}

当我使用

http://localhost:8080/myApiCall
调用服务时,云网关会将呼叫转发到
http://www.example.com/myApiCall
而不是
http://www.example.com/foobar/myApiCall

如果我将我的服务称为

http://localhost:8080/foobar/myApiCall
,则生成的调用是
http://www.example.com/foobar/myApiCall
,因此在这种情况下它可以正常工作。

基于一些调试,我的最终 URL 在这里创建: https://github.com/spring-cloud/spring-cloud-gateway/blob/v3.1.3/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/filter/RouteToRequestUrlFilter .java#L88 如果仅使用主机,则配置中会省略路径。

我使用的版本: 弹簧云网关:v3.1.3 弹簧核心:v5.3.20

我想过只使用重写路径过滤器来始终附加

/foobar/
部分 - 但没有更好的方法吗?

java spring spring-cloud spring-cloud-gateway
1个回答
0
投票

这可以使用 setPath Filter 来实现:

使用 YAML 配置它:

spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: http://www.example.com
        predicates:
        - Path=/**
        filters:
        - SetPath=/foobar

Spring Cloud Gateway MVC:https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-mvc/filters/setpath.html

Spring Cloud Gateway 响应式:https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway/gatewayfilter-factories/setpath-factory.html

© www.soinside.com 2019 - 2024. All rights reserved.