SpringCloud Gateway配置

[圖片上傳失敗...(image-709918-1615378255597)]

客戶端發(fā)送請求到gateway茵汰,由gateway handler mapping進行路由,發(fā)送到gateway web handler缀匕。這個handler處理請求相關(guān)的filter鏈。filter分“pre”和“post”兩種處理邏輯。

配置

配置predicates和filters有兩種方式:簡寫和全參數(shù)展開贺嫂。

簡寫方式

公式:name=name,regexp雁乡,例如

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue

全參數(shù)展開方式

如果yaml文件標(biāo)準(zhǔn)一樣進行配置第喳,通常會有name和args兩個鍵,args是一個map的鍵值對組配置predicate或者filter踱稍。如下:

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue

路由工廠

每種路由的判斷依據(jù)都是根據(jù)Http請求的不同屬性曲饱。

  • 匹配某時間之后的請求
  • 匹配某個時間之前的請求
  • 匹配兩個時間之間的請求
  • 匹配請求包含指定Cookie
  • 匹配請求包含指定Header
  • 匹配特定Host
  • 匹配請求方法
  • 匹配請求路徑
  • 匹配查詢參數(shù)
  • 匹配遠程地址
  • 根據(jù)權(quán)重路由

匹配某時間之后的請求

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]

**

匹配某個時間之前的請求

spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

匹配兩個時間之間的請求

spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

匹配請求包含指定Cookie

value為正則表達式

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p

匹配請求包含指定Header

value為正則表達式

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+

匹配特定Host

每個Host為Ant-style格式,以.號分割珠月。

Ant-style的匹配原則
Apache Ant樣式的路徑有三種通配符匹配方法(在下面的表格中列出)

路徑 描述
? 匹配任何單字符
* 匹配0或者任意數(shù)量的字符
** 匹配0或者更多的目錄
spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org

匹配請求方法

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST

匹配請求路徑

參數(shù)包括一個Spring PathMatcherpatterns和一個可選的matchOptionalTrailingSeparator分隔符

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}

上面的規(guī)則可以匹配諸如/red/1/red/blue/blue/green等路徑扩淀。
抽取URI中的模板變量(如segment),作為鍵值對存儲在ServerWebExchange.getAttributes()啤挎,key為ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE驻谆。這些值可以被GatewayFilter factories獲取到。有個工具方法可以更簡單地獲取到這些值庆聘。如下

Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);

String segment = uriVariables.get("segment");

匹配查詢參數(shù)

value為正則表達式

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=green

匹配遠程地址

格式為CIDR-notation胜臊,例如192.168.0.1/16,192.168.0.1是ip伙判,16是子網(wǎng)掩碼象对。

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24

根據(jù)權(quán)重路由

配置兩個參數(shù):group和weight(數(shù)值)。

spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2

上面的配置會讓80%的請求發(fā)送到weighthigh.org宴抚,20%的請求發(fā)送到weightlow.org勒魔。

網(wǎng)關(guān)過濾器工廠

AddRequestHeader

增加請求頭參數(shù)甫煞,可以使用URI變量

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}

AddRequestParameter

增加查詢參數(shù),可以使用URI變量

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}

AddResponseHeader

增加響應(yīng)頭中參數(shù)沥邻,可以使用URI變量

spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}

DedupeResponseHeader

去掉重復(fù)的響應(yīng)頭參數(shù)

spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

上面會去掉重復(fù)的Access-Control-Allow-Credentials危虱,Access-Control-Allow-Origin參數(shù)值。
可以設(shè)置strategy值修改默認(rèn)刪除策略唐全,默認(rèn)為RETAIN_FIRST埃跷,即保留第一個。其他有RETAIN_LAST邮利,RETAIN_UNIQUE弥雹。

Spring Cloud CircuitBreaker GatewayFilter Factory

輕量的斷路由

The MapRequestHeader GatewayFilter Factory

spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=Blue, X-Request-Red

可以替換頭部的參數(shù)的名稱,如將Blue:abc替換為X-Request-Red:abc

The PrefixPath GatewayFilter Factory

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=/mypath

增加前綴延届,例如/hello將被發(fā)送到/mypath/hello

The RequestRateLimiter GatewayFilter Factory
通過實現(xiàn)RateLimiter接口配置限流規(guī)則剪勿,可通過keyResolver參數(shù)設(shè)置具體的限流的key。現(xiàn)在默認(rèn)的是PrincipalNameKeyResolver方庭,調(diào)用的是ServerWebExchange 中的Principal.getName()厕吉。
如果key解析后為空,請求會被拒絕械念,可以通過配置下面參數(shù)進行自定義策略
spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key (true or false) spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code

The Redis RateLimiter

redis限流头朱,使用的是令牌桶算法。
redis-rate-limiter.replenishRate 每秒多少個請求龄减,也是令牌入桶的頻率项钮。
redis-rate-limiter.burstCapacity 峰值請求。
redis-rate-limiter.requestedTokens 每個請求消耗的令牌數(shù)希停,默認(rèn)1.
如果想保持穩(wěn)定的請求頻率烁巫,可以設(shè)置replenishRateburstCapacity 為相同值,如果有突發(fā)的大量請求宠能,則需要設(shè)置burstCapacityreplenishRate 大亚隙。
如果想設(shè)置每分鐘1個請求,可以通過以下配置實現(xiàn)
replenishRate=1
requestedTokens=60
burstCapacity=60

spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            redis-rate-limiter.requestedTokens: 1
@Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}

也可以實現(xiàn)自己的RateLimiterKeyResolver

spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"

The RedirectTo GatewayFilter Factory

配置參數(shù)status and url

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org

The RemoveRequestHeader GatewayFilter Factory

刪除指定的請求頭參數(shù)

spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo

RemoveResponseHeader GatewayFilter Factory

刪除指定響應(yīng)頭參數(shù)

spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo

The RemoveRequestParameter GatewayFilter Factory

刪除請求參數(shù)

spring:
  cloud:
    gateway:
      routes:
      - id: removerequestparameter_route
        uri: https://example.org
        filters:
        - RemoveRequestParameter=red

The RewritePath GatewayFilter Factory

重寫路徑

spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red(?<segment>/?.*), $\{segment}

上面配置會把/red/blue變?yōu)?blue

RewriteLocationResponseHeader GatewayFilter Factory

spring:
  cloud:
    gateway:
      routes:
      - id: rewritelocationresponseheader_route
        uri: http://example.org
        filters:
        - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,

The SetPath GatewayFilter Factory

spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - SetPath=/{segment}

/red/blue會變?yōu)?blue

The SetRequestHeader GatewayFilter Factory

替換請求頭參數(shù)值

spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetRequestHeader=foo, bar-{segment}

The SetResponseHeader GatewayFilter Factory

替換響應(yīng)頭參數(shù)值

spring:
  cloud:
    gateway:
      routes:
      - id: setresponseheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetResponseHeader=foo, bar-{segment}

The SetStatus GatewayFilter Factory

設(shè)置狀態(tài)碼

spring:
  cloud:
    gateway:
      routes:
      - id: setstatusstring_route
        uri: https://example.org
        filters:
        - SetStatus=BAD_REQUEST
      - id: setstatusint_route
        uri: https://example.org
        filters:
        - SetStatus=401

上面兩種配置都會設(shè)置為401

The StripPrefix GatewayFilter Factory

刪除前綴

spring:
  cloud:
    gateway:
      routes:
      - id: nameRoot
        uri: https://nameservice
        predicates:
        - Path=/name/**
        filters:
        - StripPrefix=2

上面的配置將使/name/blue/red變?yōu)閚ameservice/red违崇。

參考
https://cloud.spring.io/spring-cloud-gateway/reference/html/#the-path-route-predicate-factory

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末阿弃,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子亦歉,更是在濱河造成了極大的恐慌恤浪,老刑警劉巖畅哑,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件肴楷,死亡現(xiàn)場離奇詭異,居然都是意外死亡荠呐,警方通過查閱死者的電腦和手機赛蔫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門砂客,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人呵恢,你說我怎么就攤上這事鞠值。” “怎么了渗钉?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵彤恶,是天一觀的道長。 經(jīng)常有香客問我鳄橘,道長声离,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任瘫怜,我火速辦了婚禮术徊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘鲸湃。我一直安慰自己赠涮,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布暗挑。 她就那樣靜靜地躺著笋除,像睡著了一般。 火紅的嫁衣襯著肌膚如雪窿祥。 梳的紋絲不亂的頭發(fā)上株憾,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天,我揣著相機與錄音晒衩,去河邊找鬼嗤瞎。 笑死,一個胖子當(dāng)著我的面吹牛听系,可吹牛的內(nèi)容都是我干的贝奇。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼靠胜,長吁一口氣:“原來是場噩夢啊……” “哼掉瞳!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起浪漠,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤陕习,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后址愿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體该镣,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年响谓,在試婚紗的時候發(fā)現(xiàn)自己被綠了损合。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片省艳。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖嫁审,靈堂內(nèi)的尸體忽然破棺而出跋炕,到底是詐尸還是另有隱情,我是刑警寧澤律适,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布辐烂,位于F島的核電站,受9級特大地震影響捂贿,放射性物質(zhì)發(fā)生泄漏棉圈。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一眷蜓、第九天 我趴在偏房一處隱蔽的房頂上張望分瘾。 院中可真熱鬧,春花似錦吁系、人聲如沸德召。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽上岗。三九已至,卻和暖如春蕴坪,著一層夾襖步出監(jiān)牢的瞬間肴掷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工背传, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留呆瞻,地道東北人。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓径玖,卻偏偏與公主長得像痴脾,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子梳星,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容