简体   繁体   English

Spring Cloud Gateway API - 路由上的上下文路径不起作用

[英]Spring Cloud Gateway API - Context-path on routes not working

I have setup context-path in application.yml我在 application.yml 中设置了上下文路径

server:
  port: 4177
  max-http-header-size: 65536
  tomcat.accesslog:
    enabled: true
  servlet:
    context-path: /gb-integration

And I have configured some routes我已经配置了一些路线

@Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        final String sbl = "http://localhost:4178";

        return builder.routes()
                //gb-sbl-rest
                .route("sbl", r -> r
                        .path("/sbl/**")
                        .filters(f -> f.rewritePath("/sbl/(?<segment>.*)", "/gb-sbl/${segment}"))
                        .uri(sbl)).build();
    }

I want the API gateway to be reached using localhost:4177/gb-integration/sbl/** However it is only working on localhost:4177/sbl/**我希望使用 localhost:4177/gb-integration/sbl/** 访问 API 网关但是它仅适用于 localhost:4177/sbl/**

It seems my context-path is ignored.似乎我的上下文路径被忽略了。 Any ideas how I can get my context-path to work on all my routes?有什么想法可以让我的上下文路径在我的所有路线上工作吗?

You probably already figuered it out by your self, but here is what is working for me:您可能已经自己弄清楚了,但以下是对我有用的方法:

After reading the Spring Cloud documentation and having tryied many things on my own, I have eventually opted for a route by route configuration.在阅读了 Spring Cloud 文档并自己尝试了很多东西后,我最终选择了按路由配置的路由。 In your case, it would look something like this:在您的情况下,它看起来像这样:

.path("/gb-integration/sbl/**")

and repeat the same pattern for every route.并为每条路线重复相同的模式。

.path("/gb-integration/abc/**")
...
.path("/gb-integration/def/**")

You can actually see this in spring cloud documentation .您实际上可以在spring cloud 文档中看到这一点。

The spring clould documentation seems to be in progress. spring cloud 文档似乎正在进行中。 Hopefully, we shall find a better solution.希望我们能找到更好的解决方案。

Using yaml file like this像这样使用 yaml 文件

spring:  
  cloud:
    gateway:
      routes:
        - id: property-search-service-route
        uri: http://localhost:4178
        predicates:
          - Path=/gb-integration/sbl/**

Detailing on @sendon1982 answer详细介绍@sendon1982 答案

If your service is exposed at localhost:8080/color/red and you want it to be accessible from gateway as localhost:9090/gateway/color/red , In the Path param of predicates, prepend the /gateway , and add StripPrefix as 1 in filters, which basically translates to如果您的服务暴露在localhost:8080/color/red并且您希望它可以作为localhost:9090/gateway/color/red从网关访问,则在谓词的 Path 参数中,添加/gateway ,并将StripPrefix添加为 1在过滤器中,这基本上转化为

take the requested path which matches Path , strip/remove out the prefix paths till the number mentioned and route using given uri and the stripped path获取与Path匹配的请求路径,去除/删除前缀路径,直到提到的数字并使用给定的 uri 和去除的路径进行路由

my-app-gateway: /gateway
spring:  
  cloud:
    gateway:
      routes:
        - id: color-service
        uri: http://localhost:8080
        predicates:
          - Path=${my-app-gateway}/color/**
        filters:
          - StripPrefix=1
fixed :

application.yaml:应用程序.yaml:

gateway:
  discovery:
    locator:
      enabled: true
      lower-case-service-id: true
      filters:
        # 去掉 /ierp/[serviceId] 进行转发
        - StripPath=2
      predicates:
        - name: Path
          # 路由匹配 /ierp/[serviceId]
          # org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator#getRouteDefinitions
          args[pattern]: "'/ierp/'+serviceId+'/**'"

filter:筛选:

@Component
public class StripPathGatewayFilterFactory extends 
AbstractGatewayFilterFactory<StripPathGatewayFilterFactory.Config> {
/**
 * Parts key.
 */
public static final String PARTS_KEY = "parts";

public StripPathGatewayFilterFactory() {
    super(StripPathGatewayFilterFactory.Config.class);
}

@Override
public List<String> shortcutFieldOrder() {
    return Arrays.asList(PARTS_KEY);
}

@Override
public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
        ServerHttpRequest request = exchange.getRequest();
        ServerWebExchangeUtils.addOriginalRequestUrl(exchange, request.getURI());
        String path = request.getURI().getRawPath();
        String[] originalParts = StringUtils.tokenizeToStringArray(path, "/");

        // all new paths start with /
        StringBuilder newPath = new StringBuilder("/");
        for (int i = 0; i < originalParts.length; i++) {
            if (i >= config.getParts()) {
                // only append slash if this is the second part or greater
                if (newPath.length() > 1) {
                    newPath.append('/');
                }
                newPath.append(originalParts[i]);
            }
        }
        if (newPath.length() > 1 && path.endsWith("/")) {
            newPath.append('/');
        }

        ServerHttpRequest newRequest = request.mutate().path(newPath.toString()).contextPath(null).build();

        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

        return chain.filter(exchange.mutate().request(newRequest).build());
    };
}

public static class Config {

    private int parts;

    public int getParts() {
        return parts;
    }

    public void setParts(int parts) {
        this.parts = parts;
    }

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM