Tip: 此篇已加入.NET Core微服務基礎系列文章索引,本篇接上一篇《基於Steeltoe使用Eureka實現服務注冊與發現》,所演示的示例也是基於上一篇的基礎上而擴展的。
=> Steeltoe目錄快速導航:
1. 基於Steeltoe使用Spring Cloud Eureka
2. 基於Steeltoe使用Spring Cloud Zuul
3. 基於Steeltoe使用Spring Cloud Hystrix
一、關於Spring Cloud Zuul
API Gateway(API GW / API 網關),顧名思義,是出現在系統邊界上的一個面向API的、串行集中式的強管控服務,這里的邊界是企業IT系統的邊界。
Zuul 是Netflix 提供的一個開源組件,致力於在雲平台上提供動態路由,監控,彈性,安全等邊緣服務的框架,也有很多公司使用它來作為網關的重要組成部分。Spring Cloud 體系收錄的該模塊,主要用於提供動態路由、監控、安全控制、限流配額等,可以將內部微服務API同意暴露。

有關Zuul的更多內容,請參考我的這一篇:《Spring Cloud微服務架構學習筆記與示例》,這里不是本文重點,不再贅述。
二、快速構建Zuul Server
(1)pom.xml添加相關依賴包:本示例的版本 => Spring Boot 1.5.15.RELEASE,Spring Cloud Edgware.SR3
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- zuul -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<!-- eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- 熱啟動,熱部署依賴包,為了調試方便,加入此包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<!-- spring cloud dependencies -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
(2)啟動類添加@EnableZuulProxy注解
@SpringBootApplication @EnableZuulProxy public class ZuulServiceApplication { public static void main(String[] args) { SpringApplication.run(ZuulServiceApplication.class, args); } }
(3)添加必要配置(application.yml):主要是針對Eureka的配置,本示例將Zuul也作為一個Eureka Client注冊到Eureka Server中。
server: port: 5000 spring: application: name: zuul-gateway-service eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true # 優先注冊IP地址而不是hostname instance-id: zuul-gateway-container:${server.port} healthcheck: enabled: true # 啟用健康檢查,注意:需要引用spring boot actuator management: security: enabled: false # 默認為true,改為false以便可以看到routes
啟動Eureka Server和Zuul Server之后:

示例代碼:https://github.com/EdisonChou/Microservice.PoC.Steeltoe/tree/master/springcloud/zuul-service
三、快速驗證測試
基於第一篇的三個已注冊到Eureka的ASP.NET Core WebAPI示例項目(示例代碼:https://github.com/EdisonChou/Microservice.PoC.Steeltoe/tree/master/src/Chapter1-ServiceDiscovery),無須做任何修改,啟動並注冊到Eureka之后的服務列表:

(1)通過Zuul訪問Agent-Service

(2)通過Zuul訪問Premium-Service

(3)通過Zuul訪問Client-Service (多Client-Service實例,驗證負載均衡)

四、小結
本文極簡地介紹了一下Spring Cloud Zuul,並使用Java快速地編寫了一個API網關Zuul Server,然后基於上一篇的三個ASP.NET Core演示了一下API網關的效果。當然,對於Zuul還有很多內容,這里就不再一一演示,有興趣的童鞋或者對這種混搭式的架構感興趣的童鞋可以去了解一下。
