更新时间:2023-09-21 来源:黑马程序员 浏览量:
网关登录校验,需要经过客户端到网关再到服务器,过滤器是网关的一部分,过滤器内部可以包含两部分逻辑,分别是pre和post,分别会在请求路由到微服务之前和之后执行。
当所有Filter的pre逻辑都依次顺序执行通过后,请求才会被路由到微服务,否则会被拦截,后续过滤器不再执行。微服务返回结果后,再倒序执行Filter的post逻辑。
Netty路由过滤器负责将请求转发到微服务,当微服务返回结果后进入Filter的post阶段。
网关过滤器有两种,分别是:
GatewayFilter:路由过滤器,作用范围灵活,可以是任意指定的路由。
GlobalFilter:全局过滤器,作用范围是所有路由。
两种过滤器的过滤方法签名完全一致:
public interface GatewayFilter extends ShortcutConfigurable { Name key. String NAME_KEY - "name"; Value kkey. String VALUE_KEY = "value"; Process the Web request and (optionally/ delegate to the next WebFi Lter through the given GatewayFilterChain. Params: exchange – the current server exchange chain - provides a way to delegate to the next fiter Retums: Mono <Void> to indicate when request processing is complete MonocVoid> fiLter(ServerwebExchange exchange, GatewayFilterChain chain);
public interface GlobalFilter { Process the Web request and (optionally) delegate to the next WebFiLter through the glven GatewayFilterChain. Params: exchange - the current server exchange chain - provides a way to delegate to the next filter Returns: Mono<Voi d> to indicate when request processing is complete Mono<Void> filter(ServerwebExchange exchange, GatewayFilterChain chain);Spring内置了很多GatewayFilter和GlobalFilter,其中GlobalFilter直接对所有请求生效,而GatewayFilter则需要在yaml文件配置指定作用的路由范围。常见的GatewayFilter有:
@Component public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<Config> { @Override public GatewayFilter apply(Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 获取config值 String a = config.getA(); String b = config.getB(); String c = config.getC(); // 编写过滤器逻辑 System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); // 放行 return chain.filter(exchange); } }; } }自定义GlobalFilter就简单多了,直接实现GlobalFilter接口即可:
@Component public class PrintAnyGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 编写过滤器逻辑 System.out.println("GlobalFilter 执行了。"); // 放行 return chain.filter(exchange); } @Override public int getOrder() { // 过滤器执行顺序,值越小,优先级越高 return 0; } }