spring cloud 2.x版本 Gateway路由網(wǎng)關(guān)教程

前言

本文采用Spring cloud本文為2.1.8RELEASE,version=Greenwich.SR3

本文基于前兩篇文章eureka-server、eureka-client轻猖、eureka-ribbon和eureka-feign的實(shí)現(xiàn)强岸。
參考

概念

Spring Cloud Gateway是Spring Cloud的一個(gè)新項(xiàng)目,該項(xiàng)目是基于Spring5.0,Sprint Boot2.0和Project Reactor等技術(shù)開發(fā)的網(wǎng)關(guān),它的目的是在微服務(wù)架構(gòu)中提供一種簡單有效的統(tǒng)一api路由管理方式。
Spring Cloud Gateway目標(biāo)是要替代Netflix Zuul竟宋,其不僅提供統(tǒng)一的路由管理方式,還提供一套基于Fliter鏈的方式的網(wǎng)關(guān)其他功能形纺,比如:限流丘侠、埋點(diǎn)、安全監(jiān)控等逐样。

名稱術(shù)語

  • Route(路由):網(wǎng)關(guān)的基本模塊蜗字,它有一個(gè)id打肝、一個(gè)目標(biāo)uri、一組斷言和一組過濾器組成挪捕,如果斷言為真粗梭,則路由匹配。
  • Predicate(斷言):是一個(gè)java8的Predicate级零。輸入類型是一個(gè)ServerWebExchange断医。可以使用它來匹配來自HTTP請求的內(nèi)容奏纪。
  • Filter(過濾器):是org.springframework.cloud.gateway.filter.GatewayFilter的實(shí)例鉴嗤,可以使用它來修改請求和響應(yīng)。

流程

image

客戶端向Spring Cloud Gateway發(fā)出請求序调。如果Gateway Handler映射確定請求與路由匹配醉锅,則將其發(fā)送到Gateway Web Handler。Gateway Web Handler通過特定于請求的篩選器鏈發(fā)送請求发绢。篩選器由虛線分隔的原因是硬耍,篩選器可以在發(fā)送代理請求之前或之后執(zhí)行邏輯。執(zhí)行所有“pre”篩選邏輯边酒,然后發(fā)出代理請求默垄。在發(fā)出代理請求后,執(zhí)行“POST”篩選邏輯甚纲。

創(chuàng)建Zuul工程

1.1 創(chuàng)建sping boot工程:spring-gateway

1.2 添加pom.xml相關(guān)依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

1.3 application.yml添加配置信息

server:
  port: 8100
spring:
  application:
    name: spring-gateway
  cloud:
      gateway:
        discovery:
          locator:
            enabled: true
eureka:
  instance:
    hostname: eureka1.server.com
    lease-renewal-interval-in-seconds: 5
    lease-expiration-duration-in-seconds: 10
  client:
    service-url:
      defaultZone: http://eureka1.server.com:8701/eureka/,http://eureka2.server.com:8702/eureka/,http://eureka3.server.com:8703/eureka/

Spring.cloud.gateway.discovery.locator.enabled:true 這里先簡單使用了默認(rèn)的創(chuàng)建路由規(guī)則,自動(dòng)根據(jù)serviceid創(chuàng)建路由的功能

1.4 啟動(dòng)類SpringGatewayApplication說明

前幾片文章中都在對應(yīng)的啟動(dòng)類中增加了@EnableEurekaClient或@EnableDiscoveryClient注解,今天看文檔突然發(fā)現(xiàn)朦前,不用加@Enable*注解也可以自動(dòng)添加到注冊中心介杆,是因?yàn)樵赟pring Cloud Edgware版本之后,只要加上相關(guān)的依賴韭寸,并進(jìn)行相應(yīng)的配置就可以將服務(wù)自動(dòng)注冊到服務(wù)發(fā)現(xiàn)組件上春哨。

1.5 啟動(dòng)相關(guān)服務(wù)

按順序啟動(dòng)eureka-server、eureka-client恩伺、eureka-ribbon赴背、spring-gateway服務(wù)。
打開瀏覽器晶渠,先去eureka-server服務(wù)中心看一下服務(wù)是否正常啟動(dòng)凰荚,如下如:

image

截圖中紅框代表所有服務(wù)已經(jīng)正常啟動(dòng)。
然后新打來瀏覽器輸入:http://localhost:8100/SPRING-GATEWAY/EUREKA-RIBBON/sayHello褒脯,顯示如下:

image

因?yàn)槲覀儾庞玫氖亲詣?dòng)配置路由便瑟,所有這里url上的服務(wù)名稱要全部大寫,就是和服務(wù)注冊中心保存一致番川。
這里我可以看一下spring-gate的啟動(dòng)日志到涂,自動(dòng)路由名稱全部是大寫脊框。(個(gè)人覺得這里設(shè)計(jì)的不是很好)。

2019-10-12 16:40:35.870  INFO 97725 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty  : Flipping property: SPRING-GATEWAY.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:35.890  INFO 97725 --- [ctor-http-nio-2] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-SPRING-GATEWAY
2019-10-12 16:40:35.890  INFO 97725 --- [ctor-http-nio-2] c.netflix.loadbalancer.BaseLoadBalancer  : Client: SPRING-GATEWAY instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=SPRING-GATEWAY,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2019-10-12 16:40:35.895  INFO 97725 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2019-10-12 16:40:35.910  INFO 97725 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty  : Flipping property: SPRING-GATEWAY.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:35.911  INFO 97725 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client SPRING-GATEWAY initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=SPRING-GATEWAY,current list of Servers=[eureka1.server.com:8100],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;   Instance count:1;   Active connections count: 0;    Circuit breaker tripped count: 0;   Active connections per server: 0.0;]
},Server stats: [[Server:eureka1.server.com:8100;   Zone:defaultZone;   Total Requests:0;   Successive connection failure:0;    Total blackout seconds:0;   Last connection made:Thu Jan 01 08:00:00 CST 1970;  First connection made: Thu Jan 01 08:00:00 CST 1970;    Active Connections:0;   total failure count in last (1000) msecs:0; average resp time:0.0;  90 percentile resp time:0.0;    95 percentile resp time:0.0;    min resp time:0.0;  max resp time:0.0;  stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@3b80e99c
2019-10-12 16:40:36.008  INFO 97725 --- [tor-http-nio-10] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:36.009  INFO 97725 --- [tor-http-nio-10] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-EUREKA-RIBBON
2019-10-12 16:40:36.010  INFO 97725 --- [tor-http-nio-10] c.netflix.loadbalancer.BaseLoadBalancer  : Client: EUREKA-RIBBON instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=EUREKA-RIBBON,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2019-10-12 16:40:36.011  INFO 97725 --- [tor-http-nio-10] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2019-10-12 16:40:36.012  INFO 97725 --- [tor-http-nio-10] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:36.012  INFO 97725 --- [tor-http-nio-10] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client EUREKA-RIBBON initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=EUREKA-RIBBON,current list of Servers=[eureka1.server.com:8901],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone; Instance count:1;   Active connections count: 0;    Circuit breaker tripped count: 0;   Active connections per server: 0.0;]
},Server stats: [[Server:eureka1.server.com:8901;   Zone:defaultZone;   Total Requests:0;   Successive connection failure:0;    Total blackout seconds:0;   Last connection made:Thu Jan 01 08:00:00 CST 1970;  First connection made: Thu Jan 01 08:00:00 CST 1970;    Active Connections:0;   total failure count in last (1000) msecs:0; average resp time:0.0;  90 percentile resp time:0.0;    95 percentile resp time:0.0;    min resp time:0.0;  max resp time:0.0;  stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@19148ab

同樣的方式我可以請求eureka-feign践啄,結(jié)果如下:

image

至此基于服務(wù)發(fā)現(xiàn)的默認(rèn)路由規(guī)則就搭建完成浇雹。

1.6 自定義路由規(guī)則

1.6.1 修改application.yml配置

server:
  port: 8100
spring:
  application:
    name: spring-gateway
  cloud:
      gateway:
#        discovery:
#          locator:
#            enabled: true # 開啟通過服務(wù)中心的自動(dòng)根據(jù) serviceId 創(chuàng)建路由的功能
        routes:
          - id: ribbon-route
            uri: lb://EUREKA-RIBBON
            order: 0
            predicates:
              - Path=/ribbon/**
            filters:
              - StripPrefix=1 #去掉前綴,具體實(shí)現(xiàn)參考StripPrefixGatewayFilterFactory
              - AddResponseHeader=X-Response-Default-Foo, Default-Bar
          - id: feign-route
            uri: lb://EUREKA-FEIGN
            order: 0
            predicates:
              - Path=/feign/**
            filters:
              - StripPrefix=1
              - AddResponseHeader=X-Response-Default-Foo, Default-Bar

eureka:
  instance:
    hostname: eureka1.server.com
    lease-renewal-interval-in-seconds: 5
    lease-expiration-duration-in-seconds: 10
  client:
    service-url:
      defaultZone: http://eureka1.server.com:8701/eureka/,http://eureka2.server.com:8702/eureka/,http://eureka3.server.com:8703/eureka/

StripPrefix: 接受一個(gè)非負(fù)整數(shù)屿讽,對應(yīng)的具體實(shí)現(xiàn)是StripPrefixGatewayFilterFactory昭灵,做用是去掉前綴,整數(shù)對應(yīng)層數(shù)聂儒。在本例中訪問的/ribbon/sayHello虎锚,網(wǎng)關(guān)服務(wù)向后轉(zhuǎn)發(fā)請求的時(shí)候會(huì)去掉/ribbon,eureka-ribbon收到的請求是:/sayHello衩婚。eureka-feign同理窜护。

1.6.2 啟動(dòng)服務(wù)

訪問http://localhost:8100/ribbon/sayHellohttp://localhost:8100/feign/feign/sayHello,如圖下圖顯示:

  • ribbon:
image
  • feign:
image

1.6.3 自定義Configuration

Spring Cloud Gateway同時(shí)支持java的流式api的路由定義非春,可以和application.yml配合使用柱徙。

package spring.cloud.demo.spring.gateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RoutesConfig {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder){
        return routeLocatorBuilder.routes().route(r -> r.path("/ribbon/**")
                .filters(f -> f.stripPrefix(1)
                        .addRequestHeader("X-Response-Default-Foo", "Default-Bar"))
                .uri("lb://EUREKA-RIBBON")
                .order(0)
                .id("ribbon-route")
        ).build();
    }
}

總結(jié)

本文簡單實(shí)現(xiàn)了Spring Cloud Gateway的默認(rèn)自動(dòng)路由和自定義路由的網(wǎng)關(guān)服務(wù)。后面會(huì)繼續(xù)更新Spring Cloud Gateway的其他功能奇昙,敬請期待护侮!

代碼地址

gitHub地址


<center><font color=red>《Srping Cloud 2.X小白教程》目錄</font></center>


  • 寫作不易,轉(zhuǎn)載請注明出處储耐,喜歡的小伙伴可以關(guān)注公眾號查看更多喜歡的文章羊初。
  • 聯(lián)系方式:4272231@163.com
    image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市什湘,隨后出現(xiàn)的幾起案子长赞,更是在濱河造成了極大的恐慌,老刑警劉巖闽撤,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件得哆,死亡現(xiàn)場離奇詭異,居然都是意外死亡哟旗,警方通過查閱死者的電腦和手機(jī)贩据,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來闸餐,“玉大人饱亮,你說我怎么就攤上這事∩嵘常” “怎么了近尚?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長场勤。 經(jīng)常有香客問我戈锻,道長歼跟,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任格遭,我火速辦了婚禮哈街,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘拒迅。我一直安慰自己骚秦,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布璧微。 她就那樣靜靜地躺著作箍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪前硫。 梳的紋絲不亂的頭發(fā)上胞得,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機(jī)與錄音屹电,去河邊找鬼阶剑。 笑死,一個(gè)胖子當(dāng)著我的面吹牛危号,可吹牛的內(nèi)容都是我干的牧愁。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼外莲,長吁一口氣:“原來是場噩夢啊……” “哼猪半!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起偷线,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤办龄,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后淋昭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡安接,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年翔忽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片盏檐。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡歇式,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出胡野,到底是詐尸還是另有隱情材失,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布硫豆,位于F島的核電站龙巨,受9級特大地震影響笼呆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜旨别,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一诗赌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧秸弛,春花似錦铭若、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至绞铃,卻和暖如春镜雨,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背憎兽。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工冷离, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人纯命。 一個(gè)月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓西剥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親亿汞。 傳聞我的和親對象是個(gè)殘疾皇子瞭空,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355

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