阿里Sentinel支持Spring Cloud Gateway啦


1. 前言

4月25號,Sentinel 1.6.0 正式發布,帶來 Spring Cloud Gateway 支持、控制台登錄功能、改進的熱點限流和注解 fallback 等多項新特性,該出手時就出手,緊跟時代潮流,昨天剛發布,今天我就要給大家分享下如何使用!

2. 介紹(本段來自Sentinel文檔)

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 和 matchStrategy:為后續參數匹配特性預留,目前未實現。

用戶可以通過 GatewayRuleManager.loadRules(rules) 手動加載網關規則,或通過 GatewayRuleManager.register2Property(property) 注冊動態規則源動態推送(推薦方式)。

3. 使用

3.1 快速體驗

首先你的有一個Spring Cloud Gateway的項目,如果沒有,新建一個,增加Gateway和sentinel-spring-cloud-gateway-adapter的依賴,如下:

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
	<groupId>com.alibaba.csp</groupId>
	<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
	<version>1.6.0</version>
</dependency>

新建一個application.yml配置文件,用來配置路由:

server:
  port: 2001
spring:
  application:
    name: spring-cloud-gateway
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: http://cxytiandi.com
        predicates:
        - Path=/course

配置了Path路由,等會使用 http://localhost:2001/course 進行訪問即可。

增加一個GatewayConfiguration 類,用於配置Gateway限流要用到的類,目前是手動配置的方式,后面肯定是可以通過注解啟用,配置文件中指定限流規則的方式來使用,當然這部分工作會交給Spring Cloud Alibaba來做,后面肯定會發新版本的,大家耐心等待就行了。

@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;
    }

  
    /**
     * 配置SentinelGatewayBlockExceptionHandler,限流后異常處理
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
    	return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    /**
     * 配置SentinelGatewayFilter
     * @return
     */
    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }
    
    @PostConstruct
    public void doInit() {
        initGatewayRules();
    }

    /**
     * 配置限流規則
     */
    private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("path_route")
            .setCount(1) // 限流閾值
            .setIntervalSec(1) // 統計時間窗口,單位是秒,默認是 1 秒
        );
        GatewayRuleManager.loadRules(rules);
    }
}

我們定義的資源名稱是path_route,也就是application.yml中的路由ID,一致就行。

在一秒鍾內多次訪問http://localhost:2001/course就可以看到限流啟作用了。

限流效果

3.2 指定參數限流

上面的配置是針對整個路由來限流的,如果我們只想對某個路由的參數做限流,那么可以使用參數限流方式:

 rules.add(new GatewayFlowRule("path_route")
     .setCount(1)
     .setIntervalSec(1)
     .setParamItem(new GatewayParamFlowItem()
                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM).setFieldName("vipType")
     )
 );

通過指定PARAM_PARSE_STRATEGY_URL_PARAM表示從url中獲取參數,setFieldName指定參數名稱

3.3 自定義API分組

假設我有下面兩個路由,我想讓這兩個路由共用一個限流規則,那么我們可以自定義進行組合:

 - id: path2_route
   uri: http://cxytiandi.com
   predicates:
   - Path=/article
- id: path3_route
  uri: http://cxytiandi.com
  predicates:
  - Path=/blog/**

自定義分組代碼:

private void initCustomizedApis() {
    Set<ApiDefinition> definitions = new HashSet<>();
    ApiDefinition api1 = new ApiDefinition("customized_api")
        .setPredicateItems(new HashSet<ApiPredicateItem>() {{
         // article完全匹配
         add(new ApiPathPredicateItem().setPattern("/article"));
         // blog/開頭的
         add(new ApiPathPredicateItem().setPattern("/blog/**")
                .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX));
        }});
    definitions.add(api1);
    GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}

然后我們需要給customized_api這個資源進行配置:

 rules.add(new GatewayFlowRule("customized_api")
      .setCount(1)
      .setIntervalSec(1)
 ); 

3.4 自定義異常提示

前面我們有看到,當觸發限流后頁面顯示的是Blocked by Sentinel: FlowException,正常情況下,就算給出提示也要跟后端服務的數據格式一樣,如果你后端都是JSON格式的數據,那么異常的提示也要是JSON的格式,所以問題來了,我們怎么去自定義異常的輸出?

前面我們有配置SentinelGatewayBlockExceptionHandler,我的注釋寫的限流后異常處理,我們可以進去看下源碼就知道是不是異常處理了。下面貼出核心的代碼:

 private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
      return response.writeTo(exchange, contextSupplier.get());
 }

 @Override
 public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
      if (exchange.getResponse().isCommitted()) {
          return Mono.error(ex);
      }
      // This exception handler only handles rejection by Sentinel.
      if (!BlockException.isBlockException(ex)) {
          return Mono.error(ex);
      }
      return handleBlockedRequest(exchange, ex)
          .flatMap(response -> writeResponse(response, exchange));
 }

重點在於writeResponse這個方法,我們只要把這個方法改掉,返回自己想要返回的數據就行了,可以自定義一個SentinelGatewayBlockExceptionHandler的類來實現。

比如:

public class JsonSentinelGatewayBlockExceptionHandler implements WebExceptionHandler {
  // ........
}

然后復制SentinelGatewayBlockExceptionHandler中的代碼到JsonSentinelGatewayBlockExceptionHandler 中,只改動writeResponse一個方法即可。

private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
    ServerHttpResponse serverHttpResponse = exchange.getResponse();
    serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
    byte[] datas = "{\"code\":403,\"msg\":\"限流了\"}".getBytes(StandardCharsets.UTF_8);
    DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(datas);
    return serverHttpResponse.writeWith(Mono.just(buffer));
}

最后將配置的SentinelGatewayBlockExceptionHandler改成JsonSentinelGatewayBlockExceptionHandler 。

 @Bean
 @Order(Ordered.HIGHEST_PRECEDENCE)
 public JsonSentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
     return new JsonSentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
 }

Json格式數據提示

歡迎加入我的知識星球,一起交流技術,免費學習猿天地的課程(http://cxytiandi.com/course)

PS:目前星球中正在星主的帶領下組隊學習Spring Cloud,等你哦!

微信掃碼加入猿天地知識星球

猿天地


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM