SpringCloud課程:18.Gateway 網關服務

Gateway 網關服務

1、概述

Gateway是在Spring生態系統之上構建的API網關係統,基於Spring5 Springboot2 和Project Reactor等技術
Gateway旨在提供一種簡單而有效的方式來對API進行路由 ,以及提供一些強大的過濾器功能,例如熔斷、限流、重試等。html

 

2、做用

做用
    反向代理
    鑑權
    流量控制
    熔斷
    日誌監控java

3、三大核心概念

  • Route(路由)

    路由是構建網關的基本模塊,由ID,URI,一系列的斷言和過濾器組成,若是斷言爲true則匹配該路由web

  • Predicate 斷言

    參考java8的java.util.function.Predicate
開發人員能夠匹配HTTP請求中的全部內容(例如請求頭或請求參數),若是請求與斷言相匹配則進行路由正則表達式

  • Filter 過濾

    指Spring框架中GatewayFilter的實例,使用過濾器,能夠在請求被路由前或以後對請求進行修改spring

總結:cookie

web請求經過一些匹配條件,定位到真正的服務節點。並在這個轉發過程的先後,進行一些精細化控制
predicate就是咱們的匹配條件,
而Filter能夠理解爲一個無所不能的過濾器,有了這兩個元素再加上目標Uri 就能夠實現一個具體的路由。架構

4、Gateway工做流

客戶端向SpringCloudGateway發出請求。而後在GatewayHandlerMapping中找到與請求相匹配的路由,將其發送到GatewayWebHandler.app

Handle再經過指定的過濾鏈來將請求發送到咱們實際的服務執行業務邏輯 ,而後返回。
過濾器可能會在發送代理請求以前"pre" 或以後 「post」執行業務邏輯框架

Filter在「pre」類型的過濾器能夠作參數校驗、權限校驗、流量控制、日誌輸出、協議轉換等,在「post」類型的過濾器能夠作響應內容、響應頭的修改,日誌的輸出,流量監控等有很是重要的做用curl

5、入門配置

1.新建module cloud-gateway-gateway9527

2.pom

須要移除spring-boot-starter-web 不然報錯
    Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

<dependencies>
        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.yml

server:
  port: 9527
spring:
  application:
    name: cloud-gateway

eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    register-with-eureka: true
    fetchRegistry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

4.main

@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GateWayMain9527.class,args);
    }
}

5.經過網關訪問8001的接口

映射兩個接口

/payment/lb

/payment/get/{id}

YML新增網關配置:

    新增spring.cloud.gateway.routes部分

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route    #路由的ID,沒有固定規則但要求惟一,建議配合服務名
          uri: http://localhost:8001          #匹配後提供服務的路由地址
          predicates:
            - Path=/payment/get/**         # 斷言,路徑相匹配的進行路由
        - id: payment_routh2 #payment_route    #路由的ID,沒有固定規則但要求惟一,建議配合服務名
          uri: http://localhost:8001          #匹配後提供服務的路由地址
          predicates:
            - Path=/payment/lb/**         # 斷言,路徑相匹配的進行路由
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    register-with-eureka: true
    fetchRegistry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

 

啓動700一、cloud-provider-payment800一、9527

訪問
    http://localhost:9527/payment/get/1

6.YML配置說明

Gateway網關路由有兩種配置方式

6.1 在YML中配置

6.2 代碼中注入RouteLocator的Bean

參考:https://spring.io/projects/spring-cloud-gateway

com.zhl.springcloud.config.GateWayConfig

@Configuration
public class GateWayConfig {
    @Bean
    public RouteLocator customeRouteLocator(RouteLocatorBuilder builder){
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route_atguigu1",
                r->r.path("/guonei")
                        .uri("http://news.baidu.com/guonei")).build();
        return  routes.build();
    }
}

6.3 測試訪問

    http://localhost:9527/guonei 跳轉 http://news.baidu.com/guonei

6、經過微服務名實現動態路由

默認狀況下GateWay會根據註冊中心註冊的服務列表
以註冊中心上微服務名爲路徑建立動態路由進行轉發,從而實現動態路由的功能。

1.啓動Eureka和服務提供者 8001 8002

2.YML

    1.spring.cloud.gateway.discovery.locator.enabled:true

    2.spring.cloud.gateway.routes[0].uri:lb://cloud-payment-service #匹配後提供服務的路由地址

        spring.cloud.gateway.routes[1].uri:lb://cloud-payment-service

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #開啓從註冊中心動態建立路由的功能,利用微服務名進行路由
      routes:
        - id: payment_routh #payment_route    #路由的ID,沒有固定規則但要求惟一,建議配合服務名
          uri: lb://cloud-payment-service #匹配後提供服務的路由地址
          predicates:
            - Path=/payment/get/**         # 斷言,路徑相匹配的進行路由

        - id: payment_routh2 #payment_route    #路由的ID,沒有固定規則但要求惟一,建議配合服務名
          uri: lb://cloud-payment-service #匹配後提供服務的路由地址
          predicates:
            - Path=/payment/lb/**         # 斷言,路徑相匹配的進行路由

eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    register-with-eureka: true
    fetchRegistry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

3.測試

訪問:http://localhost:9527/payment/lb   

8001/8002

7、Predicate的使用

1.Predicate是什麼

 

2.RoutePredicateFactories 是什麼

查看啓動的後臺信息:

Spring Cloud Gateway將路由匹配做爲SpringWebFlux HandlerMapping基礎架構的一部分

Spring Cloud Gateway 包括許多內置的Route Predicate工廠。全部這些Predicate都與HTTP請求的不一樣屬性匹配。多個RoutePredicate工廠能夠進行組合

Spring Cloud Gateway建立Route對象時,使用RoutePredicateFactory建立Predicate對象,Predicate對象能夠賦值給Route。SpringCloudGateway包含許多內置的RoutePredicateFatories

3. 經常使用的Route Predicate

參考官網:

https://docs.spring.io/spring-cloud-gateway/docs/2.2.5.RELEASE/reference/html/#gateway-request-predicates-factories

 

1.After Route Predicate
    在時間以後  使用 ZonedDateTime.now() 獲取時間

- id: payment_routh2 #payment_route    #路由的ID,沒有固定規則但要求惟一,建議配合服務名
          #uri: http://localhost:8001          #匹配後提供服務的路由地址
          uri: lb://cloud-payment-service #匹配後提供服務的路由地址
          predicates:
            - Path=/payment/lb/**         # 斷言,路徑相匹配的進行路由
            - After=2020-02-21T15:51:37.485+08:00[Asia/Shanghai]

2.Before Route Predicate
    在時間以前
3.Between Route Predicate
    時間之間
4.Cookie Route Predicate

- id: payment_routh2 #payment_route    #路由的ID,沒有固定規則但要求惟一,建議配合服務名
          #uri: http://localhost:8001          #匹配後提供服務的路由地址
          uri: lb://cloud-payment-service #匹配後提供服務的路由地址
          predicates:
            - Path=/payment/lb/**         # 斷言,路徑相匹配的進行路由
            #- After=2020-02-21T15:51:37.485+08:00[Asia/Shanghai]
            - Cookie=username,zzyy

  不帶cookie訪問 

C:\Users\Administrator>curl http://localhost:9527/payment/lb
{"timestamp":"2020-12-04T14:16:14.906+00:00","path":"/payment/lb","status":404,"error":"Not Found",......

   帶上cookie訪問 

C:\Users\Administrator>curl http://localhost:9527/payment/lb  --cookie "username=zzyy"
8002

5.Header

- id: payment_routh2 #payment_route    #路由的ID,沒有固定規則但要求惟一,建議配合服務名
          uri: lb://cloud-payment-service #匹配後提供服務的路由地址
          predicates:
            - Path=/payment/lb/**         # 斷言,路徑相匹配的進行路由
            - Header=X-Request-Id, \d+  # 請求頭要有X-Request-Id屬性而且值爲整數的正則表達式
C:\Users\Administrator>curl http://localhost:9527/payment/lb  -H "X-Request-Id:1234"
8002
C:\Users\Administrator>curl http://localhost:9527/payment/lb  -H "X-Request-Id:aaaa"
{"timestamp":"2020-12-04T14:22:01.354+00:00","path":"/payment/lb","status":404,"error":"Not Found",

 

6.Host

Host Route Predicate接收一組參數,一組匹配的域名列表,這個模板時一個ant分割的模板,用.號做爲分隔符它經過參數中的主機地址做爲匹配規則。
7.Method
8.Path
9.Query
10.小結

8、Filter的使用

指的是Spring框架中GatewayFilter的實例,使用過濾器,能夠再請求被路由前或以後對請求進行修改。

路由過濾器容許以某種方式修改傳入的HTTP請求或傳出的HTTP響應。路由過濾器適用於特定路由。Spring Cloud Gateway包括許多內置的GatewayFilter工廠

1.聲明週期

    Pre  Post

2.種類

GatewayFilter:     單一的
GlobalFilter:        全局的

3.經常使用的GatewayFilter

    AddRequestParameter

4.自定義過濾器

A. 兩個主要接口

B.做用

    全局日誌記錄

    統一網關鑑權...

C.案例代碼

新增 組件 :com.zhl.springcloud.filter.MyLogGateWayFilter

@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("*****come in MyLogGateWayFilter: "+new Date());
        String name =exchange.getRequest().getQueryParams().getFirst("uname");
        if (name==null){
            log.info("***用戶名爲null ,非法用戶***");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        /*加載過濾器的順序,順序越小優先級越高*/
        return 0;
    }
}

D.測試

C:\Users\Administrator>curl http://localhost:9527/payment/lb?uname=z3
8002
相關文章
相關標籤/搜索