更新時間: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; } }