Sentinel(七)之网关限流
轉載自??網關限流
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 版本開始支持)
用戶可以通過?GatewayRuleManager.loadRules(rules)?手動加載網關規則,或通過?GatewayRuleManager.register2Property(property)?注冊動態規則源動態推送(推薦方式)。
Spring Cloud Gateway
從 1.6.0 版本開始,Sentinel 提供了 Spring Cloud Gateway 的適配模塊,可以提供兩種資源維度的限流:
- route 維度:即在 Spring 配置文件中配置的路由條目,資源名為對應的 routeId
- 自定義 API 維度:用戶可以利用 Sentinel 提供的 API 來自定義一些 API 分組
使用時需引入以下模塊(以 Maven 為例):
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-spring-cloud-gateway-adapter</artifactId><version>x.y.z</version> </dependency>使用時只需注入對應的?SentinelGatewayFilter?實例以及?SentinelGatewayBlockExceptionHandler?實例即可。比如:
@Configuration public class GatewayConfiguration {private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer) {this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {// Register the block exception handler for Spring Cloud Gateway.return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);}@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public GlobalFilter sentinelGatewayFilter() {return new SentinelGatewayFilter();} }Demo 示例:sentinel-demo-spring-cloud-gateway
比如我們在 Spring Cloud Gateway 中配置了以下路由:
server:port: 8090 spring:application:name: spring-cloud-gatewaycloud:gateway:enabled: truediscovery:locator:lower-case-service-id: trueroutes:# Add your routes here.- id: product_routeuri: lb://productpredicates:- Path=/product/**- id: httpbin_routeuri: https://httpbin.orgpredicates:- Path=/httpbin/**filters:- RewritePath=/httpbin/(?<segment>.*), /$\{segment}同時自定義了一些 API 分組:
private void initCustomizedApis() {Set<ApiDefinition> definitions = new HashSet<>();ApiDefinition api1 = new ApiDefinition("some_customized_api").setPredicateItems(new HashSet<ApiPredicateItem>() {{add(new ApiPathPredicateItem().setPattern("/product/baz"));add(new ApiPathPredicateItem().setPattern("/product/foo/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));}});ApiDefinition api2 = new ApiDefinition("another_customized_api").setPredicateItems(new HashSet<ApiPredicateItem>() {{add(new ApiPathPredicateItem().setPattern("/ahas"));}});definitions.add(api1);definitions.add(api2);GatewayApiDefinitionManager.loadApiDefinitions(definitions); }那么這里面的 route ID(如?product_route)和 API name(如?some_customized_api)都會被標識為 Sentinel 的資源。比如訪問網關的 URL 為?http://localhost:8090/product/foo/22?的時候,對應的統計會加到?product_route?和?some_customized_api?這兩個資源上面,而?http://localhost:8090/httpbin/json?只會對應到?httpbin_route?資源上面。
您可以在?GatewayCallbackManager?注冊回調進行定制:
- setBlockHandler:注冊函數用于實現自定義的邏輯處理被限流的請求,對應接口為?BlockRequestHandler。默認實現為?DefaultBlockRequestHandler,當被限流時會返回類似于下面的錯誤信息:Blocked by Sentinel: FlowException。
Zuul 1.x
Sentinel 提供了 Zuul 1.x 的適配模塊,可以為 Zuul Gateway 提供兩種資源維度的限流:
- route 維度:即在 Spring 配置文件中配置的路由條目,資源名為對應的 route ID(對應?RequestContext?中的?proxy?字段)
- 自定義 API 維度:用戶可以利用 Sentinel 提供的 API 來自定義一些 API 分組
使用時需引入以下模塊(以 Maven 為例):
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-zuul-adapter</artifactId><version>x.y.z</version> </dependency>若使用的是 Spring Cloud Netflix Zuul,我們可以直接在配置類中將三個 filter 注入到 Spring 環境中即可:
@Configuration public class ZuulConfig {@Beanpublic ZuulFilter sentinelZuulPreFilter() {// We can also provider the filter order in the constructor.return new SentinelZuulPreFilter();}@Beanpublic ZuulFilter sentinelZuulPostFilter() {return new SentinelZuulPostFilter();}@Beanpublic ZuulFilter sentinelZuulErrorFilter() {return new SentinelZuulErrorFilter();} }Sentinel Zuul Adapter 生成的調用鏈路類似于下面,其中的資源名都是 route ID 或者自定義的 API 分組名稱:
-EntranceNode: sentinel_gateway_context$$route$$another-route-b(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:8 1mb:1 1mt:9) --another-route-b(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:4 1mb:1 1mt:5) --another_customized_api(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:4 1mb:0 1mt:4) -EntranceNode: sentinel_gateway_context$$route$$my-route-1(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:6 1mb:0 1mt:6) --my-route-1(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:2 1mb:0 1mt:2) --some_customized_api(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:2 1mb:0 1mt:2)發生限流之后的處理流程 :
- 發生限流之后可自定義返回參數,通過實現?SentinelFallbackProvider?接口,默認的實現是?DefaultBlockFallbackProvider。
- 默認的 fallback route 的規則是 route ID 或自定義的 API 分組名稱。
比如:
// 自定義 FallbackProvider public class MyBlockFallbackProvider implements ZuulBlockFallbackProvider {private Logger logger = LoggerFactory.getLogger(DefaultBlockFallbackProvider.class);// you can define route as service level @Overridepublic String getRoute() {return "/book/app";}@Overridepublic BlockResponse fallbackResponse(String route, Throwable cause) {RecordLog.info(String.format("[Sentinel DefaultBlockFallbackProvider] Run fallback route: %s", route));if (cause instanceof BlockException) {return new BlockResponse(429, "Sentinel block exception", route);} else {return new BlockResponse(500, "System Error", route);}}}// 注冊 FallbackProviderZuulBlockFallbackManager.registerProvider(new MyBlockFallbackProvider());默認情況下限流后會返回 429 狀態碼,返回結果為:
{"code":429,"message":"Sentinel block exception","route":"/" }Zuul 2.x
注:從 1.7.2 版本開始支持,需要 Java 8 及以上版本。
Sentinel 提供了 Zuul 2.x 的適配模塊,可以為 Zuul Gateway 提供兩種資源維度的限流:
- route 維度:對應 SessionContext 中的?routeVIP
- 自定義 API 維度:用戶可以利用 Sentinel 提供的 API 來自定義一些 API 分組
使用時需引入以下模塊(以 Maven 為例):
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-zuul2-adapter</artifactId><version>x.y.z</version> </dependency>然后配置對應的 filter 即可:
filterMultibinder.addBinding().toInstance(new SentinelZuulInboundFilter(500)); filterMultibinder.addBinding().toInstance(new SentinelZuulOutboundFilter(500)); filterMultibinder.addBinding().toInstance(new SentinelZuulEndpoint());可以參考?sentinel-demo-zuul2-gateway 示例。
網關流控實現原理
當通過?GatewayRuleManager?加載網關流控規則(GatewayFlowRule)時,無論是否針對請求屬性進行限流,Sentinel 底層都會將網關流控規則轉化為熱點參數規則(ParamFlowRule),存儲在?GatewayRuleManager?中,與正常的熱點參數規則相隔離。轉換時 Sentinel 會根據請求屬性配置,為網關流控規則設置參數索引(idx),并同步到生成的熱點參數規則中。
外部請求進入 API Gateway 時會經過 Sentinel 實現的 filter,其中會依次進行?路由/API 分組匹配、請求屬性解析和參數組裝。Sentinel 會根據配置的網關流控規則來解析請求屬性,并依照參數索引順序組裝參數數組,最終傳入?SphU.entry(res, args)中。Sentinel API Gateway Adapter Common 模塊向 Slot Chain 中添加了一個?GatewayFlowSlot,專門用來做網關規則的檢查。GatewayFlowSlot?會從?GatewayRuleManager?中提取生成的熱點參數規則,根據傳入的參數依次進行規則檢查。若某條規則不針對請求屬性,則會在參數最后一個位置置入預設的常量,達到普通流控的效果。
網關流控控制臺
Sentinel 1.6.3 引入了網關流控控制臺的支持,用戶可以直接在 Sentinel 控制臺上查看 API Gateway 實時的 route 和自定義 API 分組監控,管理網關規則和 API 分組配置。
在 API Gateway 端,用戶只需要在原有啟動參數的基礎上添加如下啟動參數即可標記應用為 API Gateway 類型:
# 注:通過 Spring Cloud Alibaba Sentinel 自動接入的 API Gateway 整合則無需此參數 -Dcsp.sentinel.app.type=1添加正確的啟動參數并有訪問量后,我們就可以在 Sentinel 上面看到對應的 API Gateway 了。我們可以查看實時的 route 和自定義 API 分組的監控和調用信息:
?
我們可以在控制臺配置自定義的 API 分組,將一些 URL 匹配模式歸為一個 API 分組:
?
然后我們可以在控制臺針對預設的 route ID 或自定義的 API 分組配置網關流控規則:
?
云上版本可以參考?AHAS 網關流控。
總結
以上是生活随笔為你收集整理的Sentinel(七)之网关限流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 绝地求生花钱也不能变强绝地求生花钱也不能
- 下一篇: Sentinel(八)之熔断降级