更新時間:2023-09-21 來源:黑馬程序員 瀏覽量:
網(wǎng)關登錄校驗,需要經(jīng)過客戶端到網(wǎng)關再到服務器,過濾器是網(wǎng)關的一部分,過濾器內(nèi)部可以包含兩部分邏輯,分別是pre和post,分別會在請求路由到微服務之前和之后執(zhí)行。
當所有Filter的pre邏輯都依次順序執(zhí)行通過后,請求才會被路由到微服務,否則會被攔截,后續(xù)過濾器不再執(zhí)行。微服務返回結果后,再倒序執(zhí)行Filter的post邏輯。
Netty路由過濾器負責將請求轉(zhuǎn)發(fā)到微服務,當微服務返回結果后進入Filter的post階段。
網(wǎng)關過濾器有兩種,分別是:
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就簡單多了,直接實現(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; } }
【AI設計】北京143期畢業(yè)僅36天,全員拿下高薪offer!黑馬AI設計連續(xù)6期100%高薪就業(yè)
2025-09-19【跨境電商運營】深圳跨境電商運營畢業(yè)22個工作日,就業(yè)率91%+,最高薪資達13500元
2025-09-19【AI運維】鄭州運維1期就業(yè)班,畢業(yè)14個工作日,班級93%同學已拿到Offer, 一線均薪資 1W+
2025-09-19【AI鴻蒙開發(fā)】上海校區(qū)AI鴻蒙開發(fā)4期5期,距離畢業(yè)21天,就業(yè)率91%,平均薪資14046元
2025-09-19【AI大模型開發(fā)-Python】畢業(yè)33個工作日,就業(yè)率已達到94.55%,班均薪資20763元
2025-09-19【AI智能應用開發(fā)-Java】畢業(yè)5個工作日就業(yè)率98.18%,最高薪資 17.5k*13薪,全班平均薪資9244元
2025-09-19