繁体   English   中英

是否可以基于 Spring 云网关中的路径进行路由?

[英]Is it possible to route based on path in Spring Cloud Gateway?

我的问题如下:我需要根据传入路径设置网关路由,例如: http://whatever.com/get/abcd:efgh:jklm:nopq-1234-5678-90ab应该直接到http://service.com/service5因为倒数第二个破折号后面的数字是 5。因此, http://whatever.com/get/abcd:efgh:jklm:nopq-1234-8678-90ab应该指向http://service.com/service8因为倒数第二个破折号后面的数字是 8。前面的 abcd:efgh: etc 不是 static 所以它可以是任何东西,但它的格式确实有分号和破折号的确切数量,所以我猜一个正则表达式可以解决问题。 但是,我在 Path 路由谓词中找不到任何内容。 (我可以很好地使用 Query,因为它接受 REGEX,但在这种特殊情况下,我需要根据路径进行路由)。

这可能吗? 先感谢您!

您可以创建一个 RoutLocator bean 并根据您的传入路由路径定义您的目标路由。 看看这是否有帮助https://www.baeldung.com/spring-cloud-gateway#routing-handler

创建您的 CustomRoutePredicateFactory class

public class CustomRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomRoutePredicateFactory.Config> {

    public CustomRoutePredicateFactory(Class<Config> configClass) {
        super(configClass);
    }

    public Predicate<ServerWebExchange> apply(Config config) {
        return (ServerWebExchange t) -> {
            boolean result = false;

            int pathServerId = 0; // logic to extract server id from request URL
            if(config.getServerId() == pathServerId) {
                result= true;
            }
            return result;
        };
    }

    public static class Config {
        private int serverId;
        public Config(int serverId) {
            this.serverId = serverId;
        }
        public int getServerId() {
            return this.serverId;
        }
    }
}

在 RouteLocatorBuilder 中(以编程方式或配置方式)应用您的谓词工厂两次(分别为 5 和 8 次)。 下面的示例以编程方式

       .route(p -> p
             .predicate(customRoutePredicateFactory.apply(
                   new CustomRoutePredicateFactory.Config(5)))
             .uri("lb://service5")
       )

玩得开心。 享受编码。

暂无
暂无

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

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