自定義指定路由上的Gateway過濾器工廠詳解
前言
核心API
一、需求
攔截請求,打印日志
1.加依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
2.創(chuàng)建自定義過濾器 工廠
import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; @Slf4j @Component //自定義過濾器工廠的名字要以GatewayFilterFactory結(jié)尾,只需在前面加個前綴,并把前綴配到配置文件里 public class PreLogGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory { @Override public GatewayFilter apply(NameValueConfig config) { return ((exchange, chain) -> { //配置上寫的參數(shù)用config.getName(),config.getValue()來拿 //config.getName()拿到的是a,config.getValue()拿到的是b log.info("請求進來了,參數(shù):{},{}",config.getName(),config.getValue()); //Request.mutate后可以修改請求,需改后build() ServerHttpRequest modifiedRequest = exchange.getRequest().mutate().build(); //把修改后的Request給Exchange ServerWebExchange modifiedExchange = exchange.mutate().request(modifiedRequest).build(); //繼續(xù)下一個過濾器 return chain.filter(modifiedExchange); }); } }
3.加配置
spring: application: name: gateway cloud: nacos: discovery: server-addr: localhost:8848 gateway: discovery: locator: enabled: true #讓gateway在nacos上找微服務 routes: - id: before_route uri: lb://user-center #lb :nacos上的微服務 predicates: - MyTimeBetween=上午9:00,下午11:00 #指定一個路由規(guī)則,這里的MyTimeBetween是自定義的,可以使用spring-cloud-gateway自帶的。 filters: - PreLog=a,b #寫前綴即可,后面是傳給工廠的參數(shù)
4.驗證
通過gateway訪問微服務,前提是請求路徑需要滿足routes的謂詞,才會走到這個工廠里。
http://localhost:8040/users/1
到此這篇關(guān)于自定義指定路由上的Gateway過濾器工廠詳解的文章就介紹到這了,更多相關(guān)Gateway過濾器工廠內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot靜態(tài)方法調(diào)用Spring容器bean的三種解決方案
在SpringBoot中靜態(tài)方法調(diào)用Spring容器bean時出現(xiàn)的null值問題,本文就來介紹一下SpringBoot靜態(tài)方法調(diào)用Spring容器bean的三種解決方案,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學習學習吧2025-01-01解決springboot application.properties server.port配置問題
這篇文章主要介紹了解決springboot application.properties server.port配置問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08基于Springboot+Mybatis對數(shù)據(jù)訪問層進行單元測試的方式分享
本文將介紹一種快高效、可復用的解決測試方案——對數(shù)據(jù)訪問層做單元測試,文章通過代碼示例介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下2023-07-07Spring Boot攔截器Interceptor與過濾器Filter詳細教程(示例詳解)
本文詳細介紹了SpringBoot中的攔截器(Interceptor)和過濾器(Filter),包括它們的定義、作用范圍、使用場景、實現(xiàn)步驟、執(zhí)行順序、常見問題及解決方案,感興趣的朋友跟隨小編一起看看吧2025-03-03SpringBoot在項目停止(服務停止/關(guān)閉退出)之后執(zhí)行的方法
這篇文章主要給大家介紹了SpringBoot在項目停止(服務停止/關(guān)閉退出)之后執(zhí)行的兩種方法,實現(xiàn)DisposableBean接口和使用@PreDestroy注解,文中有詳細的代碼講解,具有一定的參考價值,需要的朋友可以參考下2023-12-12