API 主流網關有NGINX、ZUUL、Spring Cloud Gateway、Linkerd等;Spring Cloud Gateway構建於 Spring 5+,基於 Spring Boot 2.x 響應式的、非阻塞式的 API。同時,它支持 websockets,和 Spring 框架緊密集成,用來代替服務網關Zuul,開發體驗相對來講十分不錯。html
Spring Cloud Gateway 是 Spring Cloud 微服務平臺的一個子項目,屬於 Spring 開源社區,依賴名叫:spring-cloud-starter-gateway。 Zuul 是 Netflix 公司的開源項目,Spring Cloud 在 Netflix 項目中也已經集成了 Zuul,依賴名叫:spring-cloud-starter-netflix-zuul。git
API 網關出現的緣由是微服務架構的出現,不一樣的微服務通常會有不一樣的網絡地址,而外部客戶端可能須要調用多個服務的接口才能完成一個業務需求,若是讓客戶端直接與各個微服務通訊,會有如下的問題:github
以上這些問題能夠藉助 API 網關解決。API 網關是介於客戶端和服務器端之間的中間層,全部的外部請求都會先通過 API 網關這一層。也就是說,API 的實現方面更多的考慮業務邏輯,而安全、性能、監控能夠交由 API 網關來作,這樣既提升業務靈活性又不缺安全性。web
Spring Cloud Gateway 示例源碼spring
Spring Cloud Gateway 網關路由有兩種配置方式:後端
這兩種方式是等價的,建議使用 yml 方式進配置。跨域
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!--Spring Cloud Gateway 是使用 netty+webflux 實現所以不須要再引入 web 模塊-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
複製代碼
server:
port: 8080
spring:
cloud:
gateway:
routes:
- id: easy_route # 咱們自定義的路由 ID,保持惟一
uri: https://github.com # 目標服務地址
predicates: # 路由條件,Predicate 接受一個輸入參數,返回一個布爾值結果。該接口包含多種默認方法來將
- Path=/smltq/spring-boot-demo
複製代碼
上面這段配置的意思是,配置了一個 id 爲 easy_route 的路由規則,當訪問地址 http://localhost:8080/smltq/spring-boot-demo時會自動轉發到地址:https://github.com/smltq/spring-boot-demo。瀏覽器
在瀏覽器訪問進行測試,當咱們訪問 http://localhost:8080/smltq/spring-boot-demo 時會展現以下頁面:安全