gataway断言工作流程源码剖析
public class CookieRoutePredicateFactory
extends AbstractRoutePredicateFactory
/**
* Name key.
*/
public static final String NAME_KEY = "name";
/**
* Regexp key.
*/
public static final String REGEXP_KEY = "regexp";
public CookieRoutePredicateFactory() {
super(Config.class);
}
/*
通过shortcutFieldOrder方法设置Config配置类中的属性,需要根据具体的规则来设置
通过shortcutType方法获取具体规则,具体参看:org.springframework.cloud.gateway.support.ShortcutConfigurable.ShortcutType
规则包括以下几种:
DEFAULT : 按照shortcutFieldOrder顺序依次赋值
*/
@Override
public List
return Arrays.asList(NAME_KEY, REGEXP_KEY);
}
@Override
public Predicate
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange exchange) {
List
.get(config.name);
if (cookies == null) {
return false;
}
for (HttpCookie cookie : cookies) {
if (cookie.getValue().matches(config.regexp)) {
return true;
}
}
return false;
}
@Override
public String toString() {
return String.format("Cookie: name=%s regexp=%s", config.name,
config.regexp);
}
};
}
/*
内部配置类是用来接收在配置文件中配置的参数的
routes:
#唯一标识符
- id: hailtaxi-driver
uri: lb://hailtaxi-driver
#路由断言
predicates:
- Cookie=username,itheima
*/
@Validated
public static class Config {
@NotEmpty
private String name;
@NotEmpty
private String regexp;
public String getName() {
return name;
}
public Config setName(String name) {
this.name = name;
return this;
}
public String getRegexp() {
return regexp;
}
public Config setRegexp(String regexp) {
this.regexp = regexp;
return this;
}
}
}