Spring Cloud Gateway ---GatewayFilter過濾器、過濾器工廠(入門)

前言


在一個系統中,常常須要對特定路由進行特定操做,而微服務中網關過濾器便起到了原來單體應用中過濾器做用,對請求進行處理,本文主要介紹Spring Cloud Gateway中過濾器的基本概念,以及入門使用。html

概念


  • 一、Gateway中Filter生命週期只有兩個階段:pre和post
    pre:請求在路由以前被調用,咱們可利用這種過濾器實現身份驗證、在集羣中選擇請求的微服務、記錄調試信息等
    post:在路由到微服務之後執行。這種過濾器可用來爲響應添加標準的HttpHeader、收集統計信息和指標、將響應從微服務發送給客戶端等spring

  • 二、Spring Cloud GatewayFilter 分爲兩種:GatewayFilterGlobalFilterGlobalFilter 會應用到全部的路由上,而 GatewayFilter 將應用到單個路由或者一個分組的路由上。bash

GatewayFilter Factory


Spring Cloud Gateway中提供了不少自帶的過濾器工廠使用。咱們能夠使用其完成各類操做。
例如:使用AddRequestParameter GatewayFilter Factory給特定請求添加參數(此處使用此方法的前提是網關已經註冊到服務中心app

在網關微服務中添加以下配置,對請求爲Get方式的路由進行攔截添加參數foo=bar,並轉發到uri中ide

#此處須要注意網關服務開啓須要配置spring.cloud.gateway.discovery.locator.enabled: true
spring:
  cloud:
    gateway:
      routes:
      # =====================================
      - id: add_request_parameter_route
        uri: http://localhost:8003/provider/test
        filters:
        - AddRequestParameter=foo, bar
        predicates: 
        - Method=GET
複製代碼

在provider微服務中添加http://localhost:8003/provider/test路由方法微服務

@RestController
@RequestMapping("/provider")
public class TestController {
    @Value("${server.port}")
    private String addr;
    
    //此處須要參數名同爲foo才能接受參數foo=bar
    @GetMapping("/test")
    public String test(String foo){
        String relstr= "來自服務提供者:"+addr+" foo:"+foo;
        return relstr;
    }
}
複製代碼

啓動網關服務(9001)和provider微服務(8003),以任意路由用Get方式請求網關,測試:如圖可知訪問成功且參數添加成功 post

AddRequestHeader GatewayFilter Factory


application.yml測試

spring:
  cloud:
    gateway:
      routes:
      # 爲匹配路由請求添加請求頭X-Request-Foo, Bar
      - id: add_request_header_route
        uri: http://example.org
        filters:
        - AddRequestHeader=X-Request-Foo, Bar
複製代碼

AddResponseHeader GatewayFilter Factory


application.ymlui

spring:
   cloud:
     gateway:
       routes:
       # 爲匹配路由請求添加響應頭X-Response-Foo , Bar
       -  id:add_request_header_route
         uri:http://example.org
         過濾器:
         -  AddResponseHeader = X-Response-Foo , Bar
複製代碼

Hystrix GatewayFilter Factory


application.ymlspa

spring:
   cloud:
     gateway:
       routes:
       #
       -  id:hytstrix_route
         uri:http://example.org
         過濾器:
         -  Hystrix = myCommandName
複製代碼

其餘過濾器


參考官方文檔

  • PrefixPath GatewayFilter Factory:uri添加前綴過濾器
  • RequestRateLimiter GatewayFilter Factory
  • RedirectTo GatewayFilter Factory
相關文章
相關標籤/搜索