是否可以根据 Spring Cloud Gateway 中的路径进行路由?

时间:2021-05-07 12:53:56

标签: java 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 不是静态的,所以它可以是任何东西,但它确实有一个包含确切数量的分号和破折号的格式,所以我猜正则表达式可以做到这一点。 但是,我在 Path 路由谓词中找不到任何内容。 (我可以很好地使用 Query,因为它接受 REGEX,但在这种特殊情况下,我需要根据路径进行路由)。

这可能吗?提前致谢!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

创建您的 CustomRoutePredicateFactory 类

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")
       )

玩得开心。享受编码。

相关问题