.NET Core微服務之基於Steeltoe整合Zuul實現統一API閘道器
一、關於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之後:
三、快速驗證測試
(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還有很多內容,這裡就不再一一演示,有興趣的童鞋或者對這種混搭式的架構感興趣的童鞋可以去了解一下。
作者:周旭龍
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連結。