Spring Cloud Gateway 自定义断言(Predicate)
1、类必须是Spring组件 Bean
2、类必须加上RoutePredicateFactory作为结尾
3、类必须继承AbstractRoutePredicateFactory
4、类必须声明静态内部类,声明属性来接收配置文件中对应的断言的信息
5、需要结合shortcutFieldOrder进行绑定
6、通过apply进行逻辑判断,true:配置成功,false:配置失败
package com.wsm.predicates; import org.springframework.cloud.gateway.handler.AsyncPredicate; import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory; import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import org.springframework.web.server.ServerWebExchange; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; @Component public class CheckAuthRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactory.Config> { public CheckAuthRoutePredicateFactory() { super(CheckAuthRoutePredicateFactory.Config.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList("name"); } @Override public Predicate<ServerWebExchange> apply(CheckAuthRoutePredicateFactory.Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange serverWebExchange) { if(config.getName().equals("zhangsan")){ return true; } return false; } }; } //用于接收配置文件中断言的信息 @Validated public static class Config { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } }
- CheckAuth=zhangsan
server: port: 8060 spring: application: name: api-gateway cloud: # gateway的配置 gateway: # 路由规则 routes: - id: order_route # 路由的唯一标识, 路由到 order # uri: http://localhost:8020 # 需要转发的地址 uri: lb://order-nacos-service # 需要转发的地址 lb:使用nacos中的本地负载均衡策略 # 断言规则 用于路由规则的匹配 predicates: - Path=/order-serv/** # http://localhost:8060/order-serv/order/add 路由转到 # http://localhost:8020/order-serv/order/add # - After=2017-01-20T17:42:47.789-07:00[Asia/Shanghai] # - Header=X-Request-Id,\d+ # - Method=GET # - Query=name,zhangsan|lisi - CheckAuth=zhangsan filters: - StripPrefix=1 # 转发之前去掉第一层路径 # http://localhost:8020/order-serv/order/add 过虑成 # http://localhost:8020/order/add # 配置 Nacos nacos: server-addr: 127.0.0.1:8848 discovery: # server-addr: 127.0.0.1:8848 username: nacos password: nacos namespace: public
- CheckAuth=lisi