天天看點

SpringCloud 入門筆記(六)Zuul服務網關1 概述2 建構Zuul服務網關3 測試

目錄

1 概述

2 建構Zuul服務網關

2.1 建構gateway項目

2.2 路由配置示例

3 測試

1 概述

Zuul是Netflix開源的微服務網關,SpringCloud進行了內建,能夠非常友善地與Eureka、Ribbon等元件內建。

本篇拟采用Zuul搭建一個簡單的微服務網關。

2 建構Zuul服務網關

2.1 建構gateway項目

因為我們要将gateway注冊到服務中心,是以建構項目時,選擇Eureka Client和Zuul依賴,如下所示:

SpringCloud 入門筆記(六)Zuul服務網關1 概述2 建構Zuul服務網關3 測試

建立成功後,pom.xml會包含如下兩個選擇的依賴:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
           

編寫application.yml配置檔案,如下:

server:
  port: 8020
spring:
  application:
    name: gateway
eureka:
  client:
    service-url:
      defaultZone: http://admin:[email protected]:8000/eureka/
zuul:
  routes:
    user-ms: 
      path: /user/**
      strip-prefix: true
    role-ms: 
      path: /role/**
      strip-prefix: true

           

上面zuul.routes節點的配置中,**代表通配符,表示将 /user/ 開頭的請求路由至user-ms微服務,将 /role/ 開頭的請求路由至role-ms微服務。

2.2 路由配置示例

Zuul支援多種方式的路由配置,如下所示(參考自:《Spring Cloud與Docker微服務架構實戰》):

1. 定義指定服務的通路路徑

zuul:
  routes:
    user-ms: /u/**
    role-ms: /r/**
           

2. 忽略指定的服務

zuul:
  ignored-services: serviceA,ServiceB
           

3. 忽略所有服務

zuul:
  ignored-services: '*'
           

4. 指定服務的serviceId和路徑

zuul:
  routes:
    user: # 服務别名,可任意起名
      service-id: user-ms
      path: /u/**
           

5. 指定url和路徑

zuul:
  routes:
    github:
      path: /github/**
      url: https://github.com/GreedyStar
           

6. 路由字首

zuul:
  routes:
    user-ms: 
      path: /user/**
      strip-prefix: false
           

通路Zuul的 /user/1 路徑,請求會轉發至user-ms的/user/1

這是很常用的一種方式,在user-ms的Controller中,我們将所有請求映射至/user/路徑下,在不配置strip-prefix時,我們需要請求user-ms/user/user/list 才能正确請求到user-ms的接口。

3 測試

我們可以通過gateway來通路到指定的微服務,本篇中建立的路由規則為:

Path MicroService
/user/** user-ms localhost:8800
/role/** role-ms localhost:8801

結果如下:

SpringCloud 入門筆記(六)Zuul服務網關1 概述2 建構Zuul服務網關3 測試
SpringCloud 入門筆記(六)Zuul服務網關1 概述2 建構Zuul服務網關3 測試

源碼位址:https://github.com/GreedyStar/spring-cloud-demo

繼續閱讀