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=你好,結果如下圖

  

 

 

   

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM