阿里Sentinel支持Spring Cloud Gateway啦

1. 前言

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

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

Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模塊,此模塊中包含網關限流的規則和自定義 API 的實體和管理邏輯:json

GatewayFlowRule:網關限流規則,針對 API Gateway 的場景定製的限流規則,能夠針對不一樣 route 或自定義的 API 分組進行限流,支持針對請求中的參數、Header、來源 IP 等進行定製化的限流。後端

ApiDefinition:用戶自定義的 API 定義分組,能夠看作是一些 URL 匹配的組合。好比咱們能夠定義一個 API 叫 my_api,請求 path 模式爲 /foo/ 和 /baz/ 的都歸到 my_api 這個 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) 註冊動態規則源動態推送(推薦方式)。app

3. 使用

3.1 快速體驗

首先你的有一個Spring Cloud Gateway的項目,若是沒有,新建一個,增長Gateway和sentinel-spring-cloud-gateway-adapter的依賴,以下:ide

<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 進行訪問便可。this

增長一個GatewayConfiguration 類,用於配置Gateway限流要用到的類,目前是手動配置的方式,後面確定是能夠經過註解啓用,配置文件中指定限流規則的方式來使用,固然這部分工做會交給Spring Cloud Alibaba來作,後面確定會發新版本的,你們耐心等待就好了。url

@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,等你哦!

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

猿天地

相關文章
相關標籤/搜索