什么是 Spring Cloud Gateway(基于 WebFlux WebFlux 又基于 Netty----異步非阻塞)
Spring Cloud Gateway 是 Spring 官方基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技術(shù)開發(fā)的網(wǎng)關(guān),Spring Cloud Gateway 旨在為微服務(wù)架構(gòu)提供一種簡單而有效的統(tǒng)一的 API 路由管理方式。Spring Cloud Gateway 作為 Spring Cloud 生態(tài)系中的網(wǎng)關(guān),目標(biāo)是替代 Netflix ZUUL,其不僅提供統(tǒng)一的路由方式,并且基于 Filter 鏈的方式提供了網(wǎng)關(guān)基本的功能,例如:安全,監(jiān)控/埋點(diǎn),和限流等。
Spring Cloud Gateway 功能特征
基于 Spring Framework 5,Project Reactor 和 Spring Boot 2.0 動(dòng)態(tài)路由
Predicates 和 Filters 作用于特定路由
集成 Hystrix 斷路器
集成 Spring Cloud DiscoveryClient
易于編寫的 Predicates 和 Filters
限流
路徑重寫
Spring Cloud Gateway 工程流程
客戶端向 Spring Cloud Gateway 發(fā)出請求。然后在 Gateway Handler Mapping 中找到與請求相匹配的路由,將其發(fā)送到 Gateway Web Handler。Handler 再通過指定的過濾器鏈來將請求發(fā)送到我們實(shí)際的服務(wù)執(zhí)行業(yè)務(wù)邏輯,然后返回。
過濾器之間用虛線分開是因?yàn)檫^濾器可能會(huì)在發(fā)送代理請求之前(pre)或之后(post)執(zhí)行業(yè)務(wù)邏輯。
Getway 網(wǎng)關(guān)也需要注冊到服務(wù)注冊與發(fā)現(xiàn),也需要開啟 Feign 供用戶訪問!
創(chuàng)建一個(gè)工程名為 hello-spring-cloud-gateway 的服務(wù)消費(fèi)者項(xiàng)目,pom.xml 配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.test</groupId>
<artifactId>hello-spring-cloud-alibaba-dependencies</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../hello-spring-cloud-alibaba-dependencies/pom.xml</relativePath>
</parent>
<artifactId>hello-spring-cloud-gateway</artifactId>
<packaging>jar</packaging>
<name>hello-spring-cloud-gateway</name>
<inceptionYear>2018-Now</inceptionYear>
<dependencies>
<!-- Spring Boot Begin -->
<dependency>
<!--健康檢查-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot End -->
<!-- Spring Cloud Begin 增加了gateway 依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Spring Cloud End -->
<!-- Commons Begin gateway的過濾器等功能依然需要 Servlet 支持-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- Commons Begin -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.test.hello.spring.cloud.gateway.GatewayApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
主要增加了 org.springframework.cloud:spring-cloud-starter-gateway 依賴
特別注意:
Spring Cloud Gateway 不使用 Web 作為服務(wù)器,而是 使用 WebFlux 作為服務(wù)器,Gateway 項(xiàng)目已經(jīng)依賴了 starter-webflux,所以這里 千萬不要依賴 starter-web
由于過濾器等功能依然需要 Servlet 支持,故這里還需要依賴javax.servlet:javax.servlet-api
創(chuàng)建 Application (點(diǎn)擊項(xiàng)目 新建 /src/main/java 目錄,java 目錄下新建package----com.test.hello.spring.cloud.gateway 項(xiàng)目名命名,在包下 新建 GatewayApplication 類)
package com.test.hello.spring.cloud.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class,args);
}
}
application.yml (新建 /src/main/resources,resources 目錄下創(chuàng)建 application.yml)
spring:
application:
# 應(yīng)用名稱
name: spring-gateway
cloud:
# 使用 Naoos 作為服務(wù)注冊發(fā)現(xiàn)
nacos:
discovery:
server-addr: 127.0.0.1:8848
# 使用 Sentinel 作為熔斷器
sentinel:
transport:
port: 8721
dashboard: localhost:8080
# 路由網(wǎng)關(guān)配置
gateway:
# 設(shè)置與服務(wù)注冊發(fā)現(xiàn)組件結(jié)合,這樣可以采用服務(wù)名的路由策略
discovery:
locator:
enabled: true
# 配置路由規(guī)則
routes:
# 采用自定義路由 ID(有固定用法,不同的 id 有不同的功能,詳見:https://cloud.spring.io/spring-cloud-gateway/2.0.x/single/spring-cloud-gateway.html#gateway-route-filters)
- id: NACOS-CONSUMER
# 采用 LoadBalanceClient 方式請求,以 lb:// 開頭,后面的是注冊在 Nacos 上的服務(wù)名
uri: lb://nacos-consumer
# Predicate 翻譯過來是“謂詞”的意思,必須,主要作用是匹配用戶的請求,有很多種用法
predicates:
# Method 方法謂詞,這里是匹配 GET 和 POST 請求
- Method=GET,POST
- id: NACOS-CONSUMER-FEIGN
uri: lb://nacos-consumer-feign
predicates:
- Method=GET,POST
server:
port: 9000
# 目前無效
feign:
sentinel:
enabled: true
# 目前無效
management:
endpoints:
web:
exposure:
include: "*"
# 配置日志級別,方別調(diào)試
logging:
level:
org.springframework.cloud.gateway: debug
測試訪問 (直接通過 請求的服務(wù)名/請求)
依次運(yùn)行 Nacos Server 服務(wù)、NacosProviderApplication、NacosConsumerApplication、NacosConsumerFeignApplication、GatewayApplication
hello-nacos-nacos-consumer:8081
hello-nacos-hello Feign:8081
注意:請求方式是 http://路由網(wǎng)關(guān)IP:路由網(wǎng)關(guān)Port/服務(wù)名/**
==使用路由網(wǎng)關(guān)的全局過濾功能==
全局過濾器作用于所有的路由,不需要單獨(dú)配置,我們可以用它來實(shí)現(xiàn)很多統(tǒng)一化處理的業(yè)務(wù)需求,比如權(quán)限認(rèn)證,IP 訪問限制等等。
注意:截止 2019 年 01 月 10 日,Spring Cloud Gateway 正式版為 2.0.2 其文檔并不完善,并且有些地方還要重新設(shè)計(jì),這里僅提供一個(gè)基本的案例
創(chuàng)建全局過濾器
在 com.test.hello.spring.cloud.gateway 包下創(chuàng)建 filter 包,新建 AuthFilter 類 (用于設(shè)置全局過濾 )
實(shí)現(xiàn) GlobalFilter, Ordered 接口并在類上增加 @Component 注解就可以使用過濾功能了,非常簡單方便
package com.test.hello.spring.cloud.gateway.filter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
* 全局過濾器
*/
@Component
public class AuthFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getQueryParams().getFirst("token");
if(token==null||token.isEmpty()){
ServerHttpResponse response = exchange.getResponse();
// 封裝錯(cuò)誤信息
Map<String, Object> responseData = Maps.newHashMap();
responseData.put("code", 401);
responseData.put("message", "非法請求");
responseData.put("cause", "Token is empty");
try {
// 將信息轉(zhuǎn)換為 JSON
ObjectMapper objectMapper = new ObjectMapper();
byte[] data = objectMapper.writeValueAsBytes(responseData);
// 輸出錯(cuò)誤信息到頁面
DataBuffer buffer = response.bufferFactory().wrap(data);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
// 有 token 令牌時(shí) 進(jìn)入下一個(gè)過濾器
return chain.filter(exchange);
}
// 過濾器執(zhí)行順序的設(shè)置 越小越先執(zhí)行 默認(rèn)0
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
測試過濾器
hello-nacos-nacos-consumer:8081
附:Spring Cloud Gateway Benchmark
| Proxy |
Avg Latency |
Avg Req/Sec/Thread |
Proxy |
| gateway |
6.61ms |
3.24k |
gateway |
| linkered |
7.62ms |
2.82k |
linkered |
| zuul |
12.56ms |
2.09k |
zuul |
| none |
2.09ms |
11.77k |
none |
這里的 Zuul 為 1.x 版本,是一個(gè)基于阻塞 IO 的 API Gateway
Zuul 已經(jīng)發(fā)布了 Zuul 2.x,基于 Netty,非阻塞的,支持長連接,但 Spring Cloud 暫時(shí)還沒有整合計(jì)劃
Linkerd 基于 Scala 實(shí)現(xiàn)的、目前市面上僅有的生產(chǎn)級別的 Service Mesh(其他諸如 Istio、Conduit 暫時(shí)還不能用于生產(chǎn))。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。