spring cloud 2.x版本 Gateway路由網關教程

前言

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

本文基於前兩篇文章eureka-server、eureka-client、eureka-ribbon和eureka-feign的實現。
參考java

概念

Spring Cloud Gateway是Spring Cloud的一個新項目,該項目是基於Spring5.0,Sprint Boot2.0和Project Reactor等技術開發的網關,它的目的是在微服務架構中提供一種簡單有效的統一api路由管理方式。
Spring Cloud Gateway目標是要替代Netflix Zuul,其不只提供統一的路由管理方式,還提供一套基於Fliter鏈的方式的網關其餘功能,好比:限流、埋點、安全監控等。git

名稱術語

  • Route(路由):網關的基本模塊,它有一個id、一個目標uri、一組斷言和一組過濾器組成,若是斷言爲真,則路由匹配。
  • Predicate(斷言):是一個java8的Predicate。輸入類型是一個ServerWebExchange。可使用它來匹配來自HTTP請求的內容。
  • Filter(過濾器):是org.springframework.cloud.gateway.filter.GatewayFilter的實例,可使用它來修改請求和響應。

流程

客戶端向Spring Cloud Gateway發出請求。若是Gateway Handler映射肯定請求與路由匹配,則將其發送到Gateway Web Handler。Gateway Web Handler經過特定於請求的篩選器鏈發送請求。篩選器由虛線分隔的緣由是,篩選器能夠在發送代理請求以前或以後執行邏輯。執行全部「pre」篩選邏輯,而後發出代理請求。在發出代理請求後,執行「POST」篩選邏輯。github

建立Gateway工程

1.1 建立sping boot工程:spring-gateway

1.2 添加pom.xml相關依賴

<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 這裏先簡單使用了默認的建立路由規則,自動根據serviceid建立路由的功能web

1.4 啓動類SpringGatewayApplication說明

前幾篇文章中都在對應的啓動類中增長了@EnableEurekaClient或@EnableDiscoveryClient註解,今天看文檔忽然發現,不用加@Enable*註解也能夠自動添加到註冊中心,是由於在Spring Cloud Edgware版本以後,只要加上相關的依賴,並進行相應的配置就能夠將服務自動註冊到服務發現組件上。spring

1.5 啓動相關服務

按順序啓動eureka-server、eureka-client、eureka-ribbon、spring-gateway服務。
打開瀏覽器,先去eureka-server服務中心看一下服務是否正常啓動,以下如:

截圖中紅框表明全部服務已經正常啓動。
而後新打來瀏覽器輸入:http://localhost:8100/SPRING-GATEWAY/EUREKA-RIBBON/sayHello,顯示以下:api

由於咱們才用的是自動配置路由,全部這裏url上的服務名稱要所有大寫,就是和服務註冊中心保存一致。
這裏我能夠看一下spring-gate的啓動日誌,自動路由名稱所有是大寫。(我的以爲這裏設計的不是很好)。瀏覽器

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,結果以下:安全

至此基於服務發現的默認路由規則就搭建完成。架構

1.6 自定義路由規則

1.6.1 修改application.yml配置

server:
  port: 8100
spring:
  application:
    name: spring-gateway
  cloud:
      gateway:
#        discovery:
#          locator:
#            enabled: true # 開啓經過服務中心的自動根據 serviceId 建立路由的功能
        routes:
          - id: ribbon-route
            uri: lb://EUREKA-RIBBON
            order: 0
            predicates:
              - Path=/ribbon/**
            filters:
              - StripPrefix=1 #去掉前綴,具體實現參考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: 接受一個非負整數,對應的具體實現是StripPrefixGatewayFilterFactory,作用是去掉前綴,整數對應層數。在本例中訪問的/ribbon/sayHello,網關服務向後轉發請求的時候會去掉/ribbon,eureka-ribbon收到的請求是:/sayHello。eureka-feign同理。app

1.6.2 啓動服務

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

  • ribbon:

  • feign:

1.6.3 自定義Configuration

Spring Cloud Gateway同時支持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();
    }
}

總結

本文簡單實現了Spring Cloud Gateway的默認自動路由和自定義路由的網關服務。後面會繼續更新Spring Cloud Gateway的其餘功能,敬請期待!

代碼地址

gitHub地址


《Srping Cloud 2.X小白教程》目錄
相關文章
相關標籤/搜索