Route Predicate 组件的介绍
This is a Java 8 Function Predicate. The input type is a Spring Framework
ServerWebExchange
. This lets you match on anything from the HTTP request, such as headers or parameters.
java 8 Predicate 接口说明
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicate<T> negate() {
return (t) -> !test(t);
}
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
@SuppressWarnings("unchecked")
static <T> Predicate<T> not(Predicate<? super T> target) {
Objects.requireNonNull(target);
return (Predicate<T>)target.negate();
}
}
1:Predicate 首先这个是断言接口,所以最终的结果返回的类型是boolean, 同时支持多种形式的组合逻辑判断,比如 and , or, not(negate取反) 这三种形式。
2:predicate 例子说明:https://blog.csdn.net/u012843361/article/details/82253967
Gateway用Route Predicate做什么
1:因为我们可以在配置多个Route规则(可以通过@Bean形式或者yaml),当一个url进来的时候,一般只有一个Route会被匹配到,这个时候就需要Predicate 来判断自身和url是否匹配,假如匹配就使用当前这个Route .
2:根据特定的规则进行匹配,也可以自己扩展。扩展方法如下:
In order to write a Route Predicate you will need to implement RoutePredicateFactory. There is an abstract class called AbstractRoutePredicateFactory which you can extend.
MyRoutePredicateFactory.java
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<HeaderRoutePredicateFactory.Config> {
public MyRoutePredicateFactory() {
super(Config.class);
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
// grab configuration from Config object
return exchange -> {
//grab the request
ServerHttpRequest request = exchange.getRequest();
//take information from the request to see if it
//matches configuration.
return matches(config, request);
};
}
public static class Config {
//Put the configuration properties for your filter here
}
}
Route predicate 类图设计