因工作需要,需要使用springcloud gateway ,以.html结尾的进行路由进行websocket转发。gateway自带的8种路由规则都不能满足,故需要自定义断言规则。

一,新建一个路由断言工厂ExtCheckRoutePredicateFactory

@Component
public class ExtCheckRoutePredicateFactory extends AbstractRoutePredicateFactory<ExtCheckRoutePredicateFactory.Config> {

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

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String url=serverWebExchange.getRequest().getURI().toString();
                if(url.endsWith(".html")){
                    return true;
                }
                return false;
            }
        };
    }
    public static class Config{
        private String name;

        public String getName(){
            return name;
        }

        public void setName(String name){
            this.name=name;
        }
    }
}

如果以.html结尾,则匹配此路由

二,修改gateway配置

gateway:
    routes:
      - id: abc
        uri: http://localhost:8080
        predicates:
          - name: ExtCheck

ExtCheck即是我们新建断言工厂的前缀名,自动识别的。

这时运行发现,系统根本找不到我们自定义的断言类。
需要第三步

三,修改gateway源码,将自定义断言类加到系统 predicates里

@Bean
	public RouteLocator routeDefinitionRouteLocator(GatewayProperties properties,
													List<GatewayFilterFactory> gatewayFilters,
													List<RoutePredicateFactory> predicates,
													RouteDefinitionLocator routeDefinitionLocator,
													ConfigurationService configurationService) {
		predicates.add(new ExtCheckRoutePredicateFactory());
		return new RouteDefinitionRouteLocator(routeDefinitionLocator, predicates,
				gatewayFilters, properties, configurationService);
	}

再次运行,成功根据.html后缀转发,done!

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐