溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān)

發(fā)布時(shí)間:2021-08-03 11:31:39 來源:億速云 閱讀:142 作者:Leah 欄目:大數(shù)據(jù)

本篇文章為大家展示了spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān),內(nèi)容簡明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

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??梢允褂盟鼇砥ヅ鋪碜訦TTP請(qǐng)求的內(nèi)容。

  • Filter(過濾器):是org.springframework.cloud.gateway.filter.GatewayFilter的實(shí)例,可以使用它來修改請(qǐng)求和響應(yīng)。

流程

spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān)

客戶端向Spring Cloud Gateway發(fā)出請(qǐng)求。如果Gateway Handler映射確定請(qǐng)求與路由匹配,則將其發(fā)送到Gateway Web Handler。Gateway Web Handler通過特定于請(qǐng)求的篩選器鏈發(fā)送請(qǐng)求。篩選器由虛線分隔的原因是,篩選器可以在發(fā)送代理請(qǐng)求之前或之后執(zhí)行邏輯。執(zhí)行所有“pre”篩選邏輯,然后發(fā)出代理請(qǐng)求。在發(fā)出代理請(qǐng)求后,執(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說明

前幾片文章中都在對(duì)應(yīng)的啟動(dòng)類中增加了@EnableEurekaClient或@EnableDiscoveryClient注解,今天看文檔突然發(fā)現(xiàn),不用加@Enable*注解也可以自動(dòng)添加到注冊(cè)中心,是因?yàn)樵赟pring Cloud Edgware版本之后,只要加上相關(guān)的依賴,并進(jìn)行相應(yīng)的配置就可以將服務(wù)自動(dòng)注冊(cè)到服務(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),如下如: spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān) 截圖中紅框代表所有服務(wù)已經(jīng)正常啟動(dòng)。 然后新打來瀏覽器輸入:http://localhost:8100/SPRING-GATEWAY/EUREKA-RIBBON/sayHello,顯示如下:

spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān)

因?yàn)槲覀儾庞玫氖亲詣?dòng)配置路由,所有這里url上的服務(wù)名稱要全部大寫,就是和服務(wù)注冊(cè)中心保存一致。 這里我可以看一下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

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

spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān)

至此基于服務(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ù),對(duì)應(yīng)的具體實(shí)現(xiàn)是StripPrefixGatewayFilterFactory,做用是去掉前綴,整數(shù)對(duì)應(yīng)層數(shù)。在本例中訪問的/ribbon/sayHello,網(wǎng)關(guān)服務(wù)向后轉(zhuǎn)發(fā)請(qǐng)求的時(shí)候會(huì)去掉/ribbon,eureka-ribbon收到的請(qǐng)求是:/sayHello。eureka-feign同理。

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

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

  • ribbon:

spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān)

  • feign:

spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān)

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();
    }
}

上述內(nèi)容就是spring cloud 2.x中怎么實(shí)現(xiàn)Gateway路由網(wǎng)關(guān),你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI