更新時(shí)間:2023-09-21 來源:黑馬程序員 瀏覽量:
網(wǎng)關(guān)登錄校驗(yàn),需要經(jīng)過客戶端到網(wǎng)關(guān)再到服務(wù)器,過濾器是網(wǎng)關(guān)的一部分,過濾器內(nèi)部可以包含兩部分邏輯,分別是pre和post,分別會(huì)在請求路由到微服務(wù)之前和之后執(zhí)行。
當(dāng)所有Filter的pre邏輯都依次順序執(zhí)行通過后,請求才會(huì)被路由到微服務(wù),否則會(huì)被攔截,后續(xù)過濾器不再執(zhí)行。微服務(wù)返回結(jié)果后,再倒序執(zhí)行Filter的post邏輯。
Netty路由過濾器負(fù)責(zé)將請求轉(zhuǎn)發(fā)到微服務(wù),當(dāng)微服務(wù)返回結(jié)果后進(jìn)入Filter的post階段。
網(wǎng)關(guān)過濾器有兩種,分別是:
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內(nèi)置了很多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就簡單多了,直接實(shí)現(xiàn)GlobalFilter接口即可:
@Component public class PrintAnyGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 編寫過濾器邏輯 System.out.println("GlobalFilter 執(zhí)行了。"); // 放行 return chain.filter(exchange); } @Override public int getOrder() { // 過濾器執(zhí)行順序,值越小,優(yōu)先級越高 return 0; } }