概述
Sentinel 支援對 Spring Cloud Gateway、Zuul 等主流的 API Gateway 進行限流。
Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 子產品,此子產品中包含網關限流的規則和自定義 API 的實體和管理邏輯:
- GatewayFlowRule:網關限流規則,針對 API Gateway 的場景定制的限流規則,可以針對不同 route 或自定義的 API 分組進行限流,支援針對請求中的參數、Header、來源 IP 等進行定制化的限流。
- ApiDefinition:使用者自定義的 API 定義分組,可以看做是一些 URL 比對的組合。比如我們可以定義一個 API 叫 my_api,請求 path 模式為 /foo/** 和 /baz/** 的都歸到 my_api 這個 API 分組下面。限流的時候可以針對這個自定義的 API 分組次元進行限流。
其中網關限流規則 GatewayFlowRule 的字段解釋如下:
- resource:資源名稱,可以是網關中的 route 名稱或者使用者自定義的 API 分組名稱。
- resourceMode:規則是針對 API Gateway 的 route(RESOURCE_MODE_ROUTE_ID)還是使用者在 Sentinel 中定義的 API 分組(RESOURCE_MODE_CUSTOM_API_NAME),預設是 route。
- grade:限流名額次元,同限流規則的 grade 字段。
- count:限流門檻值
- intervalSec:統計時間視窗,機關是秒,預設是 1 秒。
- controlBehavior:流量整形的控制效果,同限流規則的 controlBehavior 字段,目前支援快速失敗和勻速排隊兩種模式,預設是快速失敗。
- burst:應對突發請求時額外允許的請求數目。
- maxQueueingTimeoutMs:勻速排隊模式下的最長排隊時間,機關是毫秒,僅在勻速排隊模式下生效。
- paramItem :參數限流配置。若不提供,則代表不針對參數進行限流,該網關規則将會被轉換成普通流控規則;否則會轉換成熱點規則。其中的字段:
- parseStrategy:從請求中提取參數的政策,目前支援提取來源 IP(PARAM_PARSE_STRATEGY_CLIENT_IP)、Host(PARAM_PARSE_STRATEGY_HOST)、任意 Header(PARAM_PARSE_STRATEGY_HEADER)和任意 URL 參數(PARAM_PARSE_STRATEGY_URL_PARAM)四種模式。
- fieldName:若提取政策選擇 Header 模式或 URL 參數模式,則需要指定對應的 header 名稱或 URL 參數名稱。
- pattern:參數值的比對模式,隻有比對該模式的請求屬性值會納入統計和流控;若為空則統計該請求屬性的所有值。(1.6.2 版本開始支援)
- matchStrategy:參數值的比對政策,目前支援精确比對(PARAM_MATCH_STRATEGY_EXACT)、子串比對(PARAM_MATCH_STRATEGY_CONTAINS)和正則比對(PARAM_MATCH_STRATEGY_REGEX)。(1.6.2 版本開始支援)
- 這些參數在內建Nacos注冊動态規則源動态推送的時候會用到,也可以通過Sentinel控制台添加,缺點就是服務重新開機所有規則都會丢失
快速開始
使用Spring Cloud Alibab能夠很友善的內建Sentinel,首先需要導入Sentinel相關的依賴
<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 配置檔案中配置的路由條目,資源名為對應的 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攔截包括了視圖、靜态資源等,需要配置viewResolvers以及攔截之後的異常,我們也可以自定義抛出異常的提示
*
* @param viewResolversProvider 視圖解析器供應器
* @param serverCodecConfigurer 伺服器編解碼器配置
*/
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();
}
/**
* 自定義異常提示:當發生限流異常時,會傳回定義的提示資訊。
*/
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", "伺服器忙,請稍後再試!");
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 網關流控預設的粒度是 route 次元以及自定義 API 分組次元,預設不支援 URL 粒度。若通過 Spring Cloud Alibaba 接入,請将 spring.cloud.sentinel.filter.enabled 配置項置為 false(若在網關流控控制台上看到了 URL 資源,就是此配置項沒有置為 false)。若使用 Spring Cloud Alibaba Sentinel 資料源子產品,需要注意網關流控規則資料源類型是 gw-flow,若将網關流控規則資料源指定為 flow 則不生效。
編寫配置檔案
在bootstrap.yaml 中編寫對應的配置
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
#預設8719端口,假如被占用會自動從8719開始依次+1掃描,直至找到未被占用的端口
port: 8719
在Nacos中對應的遠端配置檔案
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和網關,然後通路一次對應的接口,觀察Sentinel控制台
我們給user_service_test添加對應的流控規則
然後再來通路測試
如圖所示,流控生效