1. 程式人生 > 其它 >SpringCloud學習(二)——搭建Spring Cloud Gateway

SpringCloud學習(二)——搭建Spring Cloud Gateway

先看一下Spring官方對Spring Cloud Gateway的介紹:

  

 

 

Spring Cloud Gateway是為了提供一種簡單而有效的方式來路由到 API,併為它們提供橫切關注點,例如:安全性、監控/指標和彈性

Spring Cloud Gateway就好比是整個系統的大門,比如你要去坐高鐵,入口的安檢會根據高鐵站規定和你的身份判斷你是否有許可權進入,進入後讓你去哪兒候車,同時檢測你是否帶了危險品等等,而且人進入多的時候有保安攔著是否要等著一會兒進入...

下面是搭建過程(接上一篇):

1、新建module,引入spring cloud gateway和eureka-client依賴

  

 

 

2、配置application.yml檔案,內容如下:

server:
  port: 80

#指定當前eureka客戶端註冊的服務端地址
eureka:
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:8000/eureka
  instance:
    hostname: localhost

spring:
  application:
    name: cn-gateway
  profiles:
    active: path-route

---         #三個橫線表示再建立一個配置檔案
spring:
  profiles: path-route            #配置檔名 和 spring.profiles.active 相對應
  cloud:
    #設定路由規則
    gateway:
      routes:
        - id: cn-system
          uri: lb://cn-system      #代表從註冊中心獲取服務,且以lb(load-balance)負載均衡方式轉發
          predicates: #斷言
            - Path=/system
/** #表示將以/system/**開頭的請求轉發到uri為lb://cn-system的地址上 # - After=2019-06-20T00:00:00.789-07:00[America/Denver] #表示在該時間點之後的時間,發出的請求會被路由到uri filters: - StripPrefix=1 #表示將Path的路徑/system在轉發前去掉,如果設定StripPrefix=2,表示將/system/*/去掉 以此類推... 同時將spring.cloud.gateway.discovery.locator.enabled改為false,如果不改的話,之前的localhost:8001/system/hello這樣的請求地址也能正常訪問,因為這時為每個服務建立了2個router - id: cn-auth uri: lb://cn-auth predicates: - Path=/auth
/** filters: - StripPrefix=1 discovery: locator: #表示gateway開啟服務註冊和發現功能, #並且spring cloud gateway自動根據服務發現為每一個服務建立了一個router,這個router將以服務名開頭的請求路徑轉發到對應的服務 enabled: true #表示將請求路徑的服務名配置改成小寫 因為服務註冊的時候,向註冊中心註冊時將服務名轉成大寫的了 lower-case-service-id: true

3、配置啟動類,添加註解@EnableDiscoveryClient

package com.cning.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class CnGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(CnGatewayApplication.class, args);
    }

}

4、這就完成了,啟動一下我們看一下結果,為了區分出轉發效果,我在cn-auth的controller裡做了點標記

 

 

  啟動完成後瀏覽器訪問 localhost:/system/hello?msg=你好     和    localhost:/auth/hello?msg=你好,結果如下圖