5. 網關過濾器工廠
路由過濾器允許以某種方式修改傳入的HTTP請求或者傳出的HTTP響應。路由過濾器作用於特定的路由。Spring Cloud Gateway包括許多內置的網關過濾器工廠。
關於如何使用以下過濾器的更詳細示例,請查看unit tests。
5.1 AddRequestHeader GatewayFilter Factory(添加請求頭)
AddRequestHeader GatewayFilter Factory接收一個名稱和值參數。
application.yml.
spring: cloud: gateway: routes: - id: add_request_header_route uri: http://example.org filters: - AddRequestHeader=X-Request-Foo, Bar
在匹配的情況下,會為下游請求添加X-Request-Foo:Bar的header頭。
5.2 AddRequestParameter GatewayFilter Factory(添加請求參數)
AddRequestParameter GatewayFilter Factory接收一個名稱和值參數。
application.yml.
spring: cloud: gateway: routes: - id: add_request_parameter_route uri: http://example.org filters: - AddRequestParameter=foo, bar
在匹配的情況下,會為下游請求添加foo=bar的查詢字符串。
5.3 AddResponseHeader GatewayFilter Factory(添加響應頭)
AddResponseHeader GatewayFilter Factory接收一個名稱和值參數。
application.yml.
spring: cloud: gateway: routes: - id: add_request_header_route uri: http://example.org filters: - AddResponseHeader=X-Response-Foo, Bar
在匹配的情況下,會為下游響應添加X-Response-Foo:Bar的header頭。
5.4 Hystrix GatewayFilter Factory
Hystrix是Netflix的一個庫,實現了斷路器模式。Hystrix網關過濾器允許你引入斷路器到你的網關路由,
保護您的服務免於級聯故障,並允許您在發生下游故障時提供備用響應。
要在項目中啟用Hystrix網關過濾器,請添加Spring Cloud Netflix的Spring - Cloud -starter- Netflix - Hystrix的依賴。
Hystrix GatewayFilter Factory需要一個名稱參數,即HystrixCommand的名稱。
application.yml.
spring: cloud: gateway: routes: - id: hystrix_route uri: http://example.org filters: - Hystrix=myCommandName
這將剩余的過濾器封裝在命令名為myCommandName的HystrixCommand中。
Hystrix過濾器還可以接受一個可選的fallbackUri參數。目前,只支持forward:schemed uri的方式。如果調用fallback,請求將被轉發到匹配URI的controller。
application.yml.
spring: cloud: gateway: routes: - id: hystrix_route uri: lb://backing-service:8088 predicates: - Path=/consumingserviceendpoint filters: - name: Hystrix args: name: fallbackcmd fallbackUri: forward:/incaseoffailureusethis - RewritePath=/consumingserviceendpoint, /backingserviceendpoint
將觸發Hystrix fallback時將請求轉發到/incaseoffailureusethis這個URI。注意,這個示例還通過目標URI上的lb前綴演示了(可選的)Spring Cloud Netflix Ribbon負載平衡。
Hystrix設置(例如超時)可以使用全局默認值配置,也可以使用在Hystrix wiki上解釋的應用程序屬性按路由進行配置。
要為上面的示例路由設置5秒超時,將使用以下配置:
application.yml.
hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000
5.5 PrefixPath GatewayFilter Factory(前綴路徑)
PrefixPath GatewayFilter Factory接收單一的參數:
spring: cloud: gateway: routes: - id: prefixpath_route uri: http://example.org filters: - PrefixPath=/mypath
這將為所有匹配請求的路徑加上/mypath前綴。因此,對/hello的請求將被發送到/mypath/hello。
application.yml.