Sentinel網關限流與SpringCloud Gateway整合過程
網關如何限流?
Spring Cloud Gateway本身自帶的限流實現,過濾器是RequestRateLimiterGatewayFilterFactory,不過這種比較簡單,有興趣的可以實現下。
今天的重點是集成阿里的Sentinel實現網關限流,sentinel顧名思義:衛(wèi)兵;在Redis中叫做哨兵,用于監(jiān)控主從切換,但是在微服務中叫做流量防衛(wèi)兵。Sentinel 以流量為切入點,從流量控制、熔斷降級、系統(tǒng)負載保護等多個維度保護服務的穩(wěn)定性。
Sentinel 具有以下特征:
- 豐富的應用場景:Sentinel 承接了阿里巴巴近 10 年的雙十一大促流量的核心場景,例如秒殺(即突發(fā)流量控制在系統(tǒng)容量可以承受的范圍)、消息削峰填谷、集群流量控制、實時熔斷下游不可用應用等。
- 完備的實時監(jiān)控:Sentinel 同時提供實時的監(jiān)控功能。您可以在控制臺中看到接入應用的單臺機器秒 級數據,甚至 500 臺以下規(guī)模的集群的匯總運行情況。
- 廣泛的開源生態(tài):Sentinel 提供開箱即用的與其它開源框架/庫的整合模塊,例如與 Spring Cloud、Apache Dubbo、gRPC、Quarkus 的整合。您只需要引入相應的依賴并進行簡單的配置即可快速地接入 Sentinel。同時 Sentinel 提供 Java/Go/C++ 等多語言的原生實現。
- 完善的 SPI 擴展機制:Sentinel 提供簡單易用、完善的 SPI 擴展接口。您可以通過實現擴展接口來快速地定制邏輯。例如定制規(guī)則管理、適配動態(tài)數據源等。
Sentinel 的主要特性如下圖:

從1.6.0版本開始,Sentinel提供了SpringCloud Gateway的適配模塊,可以提供兩種資源維度的限流:
**route維度:**即在配置文件中配置的路由條目,資源名為對應的routeId,這種屬于粗粒度的限流,一般是對某個微服務進行限流。
**自定義API維度:**用戶可以利用Sentinel提供的API來自定義一些API分組,這種屬于細粒度的限流,針對某一類的uri進行匹配限流,可以跨多個微服務。
項目實踐
新建一個gateway-service模塊,添加如下依賴:
<!--nacos注冊中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--spring cloud gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- spring cloud gateway整合sentinel的依賴-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<!-- sentinel的依賴-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>配置文件
配置文件中主要指定以下三種配置:
- nacos的地址
- sentinel控制臺的地址
- 網關路由的配置
配置如下
server:
port: 8100
logging:
path: d:/
spring:
application:
name: gateway-service
cloud:
nacos:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
gateway:
routes:
- id: mqtt-service-route
uri: lb://mqtt-service
predicates:
- Path=/mqtt/**
- id: usermgr-service-route
uri: lb://usermgr-service
predicates:
- Path=/usermgr/**上述配置中設置了一個路由usermgr-service-route,只要請求路徑滿足http://127.0.0.1:8100/usermgr/user/id都會被路由到usermgr-service這個服務中
限流配置
經過上述兩個步驟其實已經整合好了Sentinel,此時訪問一下接口:http://127.0.0.1:8100/usermgr/user/id
然后在sentinel控制臺可以看到已經被監(jiān)控了,監(jiān)控的路由是usermgr-service,如下圖:

上圖中對usermgr-service這個路由做出了限流,QPS閾值為1。
此時快速訪問:http://127.0.0.1:8100/usermgr/user/id,看到已經被限流了,如下圖:

以上route維度的限流已經配置成功,小伙伴可以自己照著上述步驟嘗試一下。
API分組限流
首先需要定義一個分組,API管理-> 新增API分組,如下圖:

匹配模式選擇了精確匹配(還有前綴匹配,正則匹配),因此只有這個uri:http://127.0.0.1:8100/usermgr/user/id會被限流。
第二步需要對這個分組添加流控規(guī)則,流控規(guī)則->新增網關流控,如下圖

API名稱那里選擇對應的分組即可,新增之后,限流規(guī)則就生效了。
如何自定義限流異常信息?
從上面的演示中可以看到默認的異常返回信息是:“Block…”,這種肯定是客戶端不能接受的,因此需要定制自己的異常返回信息。
下面介紹兩種不同的方式定制異常返回信息,開發(fā)中自己選擇其中一種。
直接配置文件中定制
開發(fā)者可以直接在配置文件中直接修改返回信息,配置如下:
spring:
cloud:
## 整合sentinel,配置sentinel控制臺的地址
sentinel:
#配置限流之后,響應內容
scg:
fallback:
## 兩種模式,一種是response返回文字提示信息,
## 一種是redirect,重定向跳轉,需要同時配置redirect(跳轉的uri)
mode: response
## 響應的狀態(tài)
response-status: 200
## 響應體
response-body: '{"code": 200,"message": "請求失敗,稍后重試!"}'上述配置中mode配置的是response,一旦被限流了,將會返回JSON串
{
"code": 200,
"message": "請求失敗,稍后重試!"
}重定向的配置
如下:
spring:
cloud:
## 整合sentinel,配置sentinel控制臺的地址
sentinel:
#配置限流之后,響應內容
scg:
fallback:
## 兩種模式,一種是response返回文字提示信息,一種是redirect,重定向跳轉,需要同時配置redirect(跳轉的uri)
mode: redirect
## 跳轉的URL
redirect: http://www.baidu.com一旦被限流,將會直接跳轉到:http://www.baidu.com
編碼定制
這種就不太靈活了,通過硬編碼的方式,完整代碼如下:
package com.spacetime.gateway.config;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class GatewayConfig {
/**
* 自定義限流處理器
*/
@PostConstruct
public void initBlockHandlers() {
BlockRequestHandler blockHandler = (serverWebExchange, throwable) -> {
Map map = new HashMap();
map.put("code",200);
map.put("message","請求失敗,稍后重試!");
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(map));
};
GatewayCallbackManager.setBlockHandler(blockHandler);
}
}總結
文章介紹了Spring Cloud Gateway整合Sentinel對網關層進行限流,以及關于限流的一些思考。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Springboot中Dependency not found解決方案
本文主要介紹了Springboot中Dependency not found解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11

