Spring?Cloud?Gateway集成Sentinel流控詳情
概述
Sentinel 支持對 Spring Cloud Gateway、Zuul 等主流的 API Gateway 進行限流。

Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模塊,此模塊中包含網(wǎng)關(guān)限流的規(guī)則和自定義 API 的實體和管理邏輯:
GatewayFlowRule:網(wǎng)關(guān)限流規(guī)則,針對 API Gateway 的場景定制的限流規(guī)則,可以針對不同 route 或自定義的 API 分組進行限流,支持針對請求中的參數(shù)、Header、來源 IP 等進行定制化的限流。ApiDefinition:用戶自定義的 API 定義分組,可以看做是一些 URL 匹配的組合。比如我們可以定義一個 API 叫my_api,請求 path 模式為/foo/**和/baz/**的都?xì)w到my_api這個 API 分組下面。限流的時候可以針對這個自定義的 API 分組維度進行限流。
其中網(wǎng)關(guān)限流規(guī)則 GatewayFlowRule 的字段解釋如下:
resource:資源名稱,可以是網(wǎng)關(guān)中的 route 名稱或者用戶自定義的 API 分組名稱。resourceMode:規(guī)則是針對 API Gateway 的 route(RESOURCE_MODE_ROUTE_ID)還是用戶在 Sentinel 中定義的 API 分組(RESOURCE_MODE_CUSTOM_API_NAME),默認(rèn)是 route。grade:限流指標(biāo)維度,同限流規(guī)則的grade字段。count:限流閾值intervalSec:統(tǒng)計時間窗口,單位是秒,默認(rèn)是 1 秒。controlBehavior:流量整形的控制效果,同限流規(guī)則的controlBehavior字段,目前支持快速失敗和勻速排隊兩種模式,默認(rèn)是快速失敗。burst:應(yīng)對突發(fā)請求時額外允許的請求數(shù)目。maxQueueingTimeoutMs:勻速排隊模式下的最長排隊時間,單位是毫秒,僅在勻速排隊模式下生效。paramItem:參數(shù)限流配置。若不提供,則代表不針對參數(shù)進行限流,該網(wǎng)關(guān)規(guī)則將會被轉(zhuǎn)換成普通流控規(guī)則;否則會轉(zhuǎn)換成熱點規(guī)則。其中的字段:
這些參數(shù)在集成Nacos注冊動態(tài)規(guī)則源動態(tài)推送的時候會用到,也可以通過Sentinel控制臺添加,缺點就是服務(wù)重啟所有規(guī)則都會丟失
parseStrategy:從請求中提取參數(shù)的策略,目前支持提取來源 IP(PARAM_PARSE_STRATEGY_CLIENT_IP)、Host(PARAM_PARSE_STRATEGY_HOST)、任意 Header(PARAM_PARSE_STRATEGY_HEADER)和任意 URL 參數(shù)(PARAM_PARSE_STRATEGY_URL_PARAM)四種模式。fieldName:若提取策略選擇 Header 模式或 URL 參數(shù)模式,則需要指定對應(yīng)的 header 名稱或 URL 參數(shù)名稱。pattern:參數(shù)值的匹配模式,只有匹配該模式的請求屬性值會納入統(tǒng)計和流控;若為空則統(tǒng)計該請求屬性的所有值。(1.6.2 版本開始支持)matchStrategy:參數(shù)值的匹配策略,目前支持精確匹配(PARAM_MATCH_STRATEGY_EXACT)、子串匹配(PARAM_MATCH_STRATEGY_CONTAINS)和正則匹配(PARAM_MATCH_STRATEGY_REGEX)。(1.6.2 版本開始支持)
快速開始
使用Spring Cloud Alibab能夠很方便的集成Sentinel,首先需要導(dǎo)入Sentinel相關(guān)的依賴
? ? ? ?<dependency> ? ? ? ? ? ?<groupId>com.alibaba.cloud</groupId> ? ? ? ? ? ?<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> ? ? ? ?</dependency> ? ? ? ?<dependency> ? ? ? ? ? ?<groupId>com.alibaba.csp</groupId> ? ? ? ? ? ?<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId> ? ? ? ? ? ?<version>1.8.3</version> ? ? ? ?</dependency>
從 1.6.0 版本開始,Sentinel 提供了 Spring Cloud Gateway 的適配模塊,可以提供兩種資源維度的限流:
- route 維度:即在 Spring 配置文件中配置的路由條目,資源名為對應(yīng)的 routeId
- 自定義 API 維度:用戶可以利用 Sentinel 提供的 API 來自定義一些 API 分組
添加Sentinel配置文件
package cuit.epoch.pymjl.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.annotation.PostConstruct;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @author Pymjl
* @version 1.0
* @date 2022/9/15 14:15
**/
@Configuration
public class GatewayConfiguration {
? private final List<ViewResolver> viewResolvers;
? private final ServerCodecConfigurer serverCodecConfigurer;
?
? ?/**
? ? * 這里ServerCodecConfigurer會報錯:“Could not autowire. No beans of 'ServerCodecConfigurer' type found.”
? ? * 不影響使用,可以忽略他
? ? * sentinel攔截包括了視圖、靜態(tài)資源等,需要配置viewResolvers以及攔截之后的異常,我們也可以自定義拋出異常的提示
? ? *
? ? * @param viewResolversProvider 視圖解析器供應(yīng)器
? ? * @param serverCodecConfigurer 服務(wù)器編解碼器配置
? ? */
? public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ServerCodecConfigurer serverCodecConfigurer) {
? ? ? this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
? ? ? this.serverCodecConfigurer = serverCodecConfigurer;
? ?}
?
? ?/**
? ? * 由于sentinel的工作原理其實借助于全局的filter進行請求攔截并計算出是否進行限流、熔斷等操作的,增加SentinelGateWayFilter配置
? ? *
? ? * @return {@code SentinelGatewayBlockExceptionHandler}
? ? */
? ?@Bean
? ?@Order(Ordered.HIGHEST_PRECEDENCE)
? public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
? ? ? // Register the block exception handler for Spring Cloud Gateway.
? ? ? ?return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
? ?}
? ?@Bean
? ?@Order(-1)
? public GlobalFilter sentinelGatewayFilter() {
? ? ? ?return new SentinelGatewayFilter();
? ?}
?
? ?@PostConstruct
? public void doInit() {
? ? ? initCustomizedApis();
? ?}
?
? ?/**
? ? * 自定義異常提示:當(dāng)發(fā)生限流異常時,會返回定義的提示信息。
? ? */
? private void initCustomizedApis() {
? ? ? BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
? ? ? ? ? ?@Override
? ? ? ? ? public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
? ? ? ? ? ? ? // 自定義異常處理
? ? ? ? ? ? ? HashMap<String, String> map = new HashMap<>();
? ? ? ? ? ? ? map.put("code", "10099");
? ? ? ? ? ? ? map.put("message", "服務(wù)器忙,請稍后再試!");
? ? ? ? ? ? ? ?return ServerResponse.status(HttpStatus.NOT_ACCEPTABLE)
? ? ? ? ? ? ? ? ? ? ? ?.contentType(MediaType.APPLICATION_JSON)
? ? ? ? ? ? ? ? ? ? ? ?.body(BodyInserters.fromValue(map));
? ? ? ? ? ?}
? ? ? ?};
? ? ? GatewayCallbackManager.setBlockHandler(blockRequestHandler);
? ?}
}除此之外,用戶可以利用 Sentinel 提供的 API 來自定義一些 API 分組,然后Sentinel會針對這個分組進行限流,
示例如下:
? ?@PostConstruct
? ?public void doInit() {
? ? ? ?initCustomizedApis();
? }
private void initCustomizedApis() {
? ? ? ?Set<ApiDefinition> definitions = new HashSet<>();
? ? ? ?ApiDefinition api1 = new ApiDefinition("some_customized_api")
? ? ? ? ? .setPredicateItems(new HashSet<ApiPredicateItem>() {{
? ? ? ? ? ? ? ?add(new ApiPathPredicateItem().setPattern("/ahas"));
? ? ? ? ? ? ? ?add(new ApiPathPredicateItem().setPattern("/product/**")
? ? ? ? ? ? ? ? ? .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
? ? ? ? ? }});
? ? ? ?ApiDefinition api2 = new ApiDefinition("another_customized_api")
? ? ? ? ? .setPredicateItems(new HashSet<ApiPredicateItem>() {{
? ? ? ? ? ? ? ?add(new ApiPathPredicateItem().setPattern("/**")
? ? ? ? ? ? ? ? ? .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
? ? ? ? ? }});
? ? ? ?definitions.add(api1);
? ? ? ?definitions.add(api2);
? ? ? ?GatewayApiDefinitionManager.loadApiDefinitions(definitions);
? }注意:
- Sentinel 網(wǎng)關(guān)流控默認(rèn)的粒度是 route 維度以及自定義 API 分組維度,默認(rèn)不支持 URL 粒度。若通過 Spring Cloud Alibaba 接入,請將
spring.cloud.sentinel.filter.enabled配置項置為 false(若在網(wǎng)關(guān)流控控制臺上看到了 URL 資源,就是此配置項沒有置為 false)。- 若使用 Spring Cloud Alibaba Sentinel 數(shù)據(jù)源模塊,需要注意網(wǎng)關(guān)流控規(guī)則數(shù)據(jù)源類型是
gw-flow,若將網(wǎng)關(guān)流控規(guī)則數(shù)據(jù)源指定為 flow 則不生效。
編寫配置文件
在bootstrap.yaml 中編寫對應(yīng)的配置
spring: application: ? name: gateway-service cloud: ? loadbalancer: ? ? nacos: ? ? ? enabled: true ? nacos: ? ? discovery: ? ? ? server-addr: 192.168.199.128:8848 #Nacos地址 ? ? config: ? ? ? server-addr: 192.168.199.128:8848 #Nacos地址 ? ? ? file-extension: yaml #這里我們獲取的yaml格式的配置 ? gateway: ? ? discovery: ? ? ? locator: ? ? ? ? enabled: true ? sentinel: ? ? filter: ? ? ? enabled: false ? ? transport: ? ? ? ?#配置 Sentinel dashboard 地址 ? ? ? dashboard: 192.168.199.128:8858 ? ? ? ?#默認(rèn)8719端口,假如被占用會自動從8719開始依次+1掃描,直至找到未被占用的端口 ? ? ? port: 8719
在Nacos中對應(yīng)的遠程配置文件:
spring:
cloud:
? gateway:
? ?# 全局的過濾器,跨域配置
? ? default-filters:
? ? ? - DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_UNIQUE
? ? globalcors:
? ? ? cors-configurations:
? ? ? ? '[/**]':
? ? ? ? ? allowedHeaders: '*'
? ? ? ? ? allowedMethods: '*'
? ? ? ? ? allowedOrigins: '*'
? ? ?# 路由
? ? routes:
? ? ? - id: user_servcie_get
? ? ? ? uri: lb://user-service
? ? ? ? predicates:
? ? ? ? ? - Path=/user/get/{id}
? ? ? - id: user_service_test
? ? ? ? uri: lb://user-service
? ? ? ? predicates:
? ? ? ? ? - Path=/user/test測試
先啟動userservice和網(wǎng)關(guān),然后訪問一次對應(yīng)的接口,觀察Sentinel控制臺

我們給user_service_test添加對應(yīng)的流控規(guī)則:

然后再來訪問測試:

如圖所示,流控生效
到此這篇關(guān)于Spring Cloud Gateway集成Sentinel流控詳情的文章就介紹到這了,更多相關(guān)Spring Cloud Gateway集成Sentinel 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用poi-tl設(shè)置word圖片環(huán)繞方式為浮于在文字上方
POI-TL 是一個基于 Apache POI 的 Java 庫,專注于在 Microsoft Word 文檔(.docx 格式)中進行模板填充和動態(tài)內(nèi)容生成,下面我們看看如何使用poi-tl設(shè)置word圖片環(huán)繞方式為浮于在文字上方吧2025-03-03
Idea調(diào)用WebService的關(guān)鍵步驟和注意事項
這篇文章主要介紹了如何在Idea中調(diào)用WebService,包括理解WebService的基本概念、獲取WSDL文件、閱讀和理解WSDL文件、選擇對接測試工具或方式、發(fā)送請求和接收響應(yīng)、處理響應(yīng)結(jié)果以及錯誤處理,需要的朋友可以參考下2025-01-01
基于java實現(xiàn)websocket協(xié)議過程詳解
這篇文章主要介紹了基于java實現(xiàn)websocket協(xié)議過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09

