亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

阿里Sentinel支持Spring Cloud Gateway啦

chengtao1633 / 946人閱讀

摘要:應(yīng)對突發(fā)請求時額外允許的請求數(shù)目。勻速排隊模式下的最長排隊時間,單位是毫秒,僅在勻速排隊模式下生效。和為后續(xù)參數(shù)匹配特性預(yù)留,目前未實現(xiàn)。

1. 前言

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

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

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 分組進(jìn)行限流,支持針對請求中的參數(shù)、Header、來源 IP 等進(jìn)行定制化的限流。

ApiDefinition:用戶自定義的 API 定義分組,可以看做是一些 URL 匹配的組合。比如我們可以定義一個 API 叫 my_api,請求 path 模式為 /foo/ 和 /baz/ 的都?xì)w到 my_api 這個 API 分組下面。限流的時候可以針對這個自定義的 API 分組維度進(jìn)行限流。

其中網(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ù)進(jìn)行限流,該網(wǎng)關(guān)規(guī)則將會被轉(zhuǎn)換成普通流控規(guī)則;否則會轉(zhuǎn)換成熱點規(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 和 matchStrategy:為后續(xù)參數(shù)匹配特性預(yù)留,目前未實現(xiàn)。

用戶可以通過 GatewayRuleManager.loadRules(rules) 手動加載網(wǎng)關(guān)規(guī)則,或通過 GatewayRuleManager.register2Property(property) 注冊動態(tài)規(guī)則源動態(tài)推送(推薦方式)。

3. 使用 3.1 快速體驗

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


    org.springframework.cloud
    spring-cloud-starter-gateway


    com.alibaba.csp
    sentinel-spring-cloud-gateway-adapter
    1.6.0

新建一個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 進(jìn)行訪問即可。

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

@Configuration
public class GatewayConfiguration {

    private final List viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfiguration(ObjectProvider> 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();
    }

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

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

在一秒鐘內(nèi)多次訪問http://localhost:2001/course就可以看到限流啟作用了。

3.2 指定參數(shù)限流

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

 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中獲取參數(shù),setFieldName指定參數(shù)名稱

3.3 自定義API分組

假設(shè)我有下面兩個路由,我想讓這兩個路由共用一個限流規(guī)則,那么我們可以自定義進(jìn)行組合:

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

自定義分組代碼:

private void initCustomizedApis() {
    Set definitions = new HashSet<>();
    ApiDefinition api1 = new ApiDefinition("customized_api")
        .setPredicateItems(new HashSet() {{
         // 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這個資源進(jìn)行配置:

 rules.add(new GatewayFlowRule("customized_api")
      .setCount(1)
      .setIntervalSec(1)
 ); 
3.4 自定義異常提示

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

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

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

 @Override
 public Mono 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這個方法,我們只要把這個方法改掉,返回自己想要返回的數(shù)據(jù)就行了,可以自定義一個SentinelGatewayBlockExceptionHandler的類來實現(xiàn)。

比如:

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

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

private Mono 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);
 }

歡迎加入我的知識星球,一起交流技術(shù),免費學(xué)習(xí)猿天地的課程(http://cxytiandi.com/course) PS:目前星球中正在星主的帶領(lǐng)下組隊學(xué)習(xí)Spring Cloud,等你哦!

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/74315.html

相關(guān)文章

  • 阿里Sentinel整合Zuul網(wǎng)關(guān)詳解

    摘要:前面我們講解了整合,詳細(xì)請查看文章阿里支持啦目前來說,大部分公司線上的網(wǎng)關(guān)應(yīng)該是,所以今天我們就來看看如何在中整合。 前面我們講解了Sentinel整合Spring Cloud Gateway,詳細(xì)請查看文章:阿里Sentinel支持Spring Cloud Gateway啦 目前來說,大部分公司線上的網(wǎng)關(guān)應(yīng)該是Zuul,所以今天我們就來看看如何在Zuul中整合Sentinel。本來想...

    miqt 評論0 收藏0
  • Spring Cloud Gateway 擴(kuò)展支持動態(tài)限流

    摘要:以流量為切入點,從流量控制熔斷降級系統(tǒng)負(fù)載保護(hù)等多個維度保護(hù)服務(wù)的穩(wěn)定性分布式系統(tǒng)的流量防衛(wèi)兵。歡迎關(guān)注我們獲得更多的好玩實踐 之前分享過 一篇 《Spring Cloud Gateway 原生的接口限流該怎么玩》, 核心是依賴Spring Cloud Gateway 默認(rèn)提供的限流過濾器來實現(xiàn) 原生RequestRateLimiter 的不足 配置方式 spring: clou...

    妤鋒シ 評論0 收藏0
  • Spring Cloud Gateway 擴(kuò)展支持動態(tài)限流

    摘要:以流量為切入點,從流量控制熔斷降級系統(tǒng)負(fù)載保護(hù)等多個維度保護(hù)服務(wù)的穩(wěn)定性分布式系統(tǒng)的流量防衛(wèi)兵。歡迎關(guān)注我們獲得更多的好玩實踐 之前分享過 一篇 《Spring Cloud Gateway 原生的接口限流該怎么玩》, 核心是依賴Spring Cloud Gateway 默認(rèn)提供的限流過濾器來實現(xiàn) 原生RequestRateLimiter 的不足 配置方式 spring: clou...

    beanlam 評論0 收藏0
  • Sentinel: 分布式系統(tǒng)的流量防衛(wèi)兵

    摘要:有沒有那么一個框架能夠把熔斷跟限流都給做了,以前沒有,但是現(xiàn)在有了,我這屬于自問自答哈這個框架就是阿里最新開源的。后來我才發(fā)現(xiàn)我錯了,大錯特錯,這是一個新的框架,潛力實力阿里開源。 前言 在 Spring Cloud 體系中,熔斷降級我們會使用 Hystrix 框架,限流通常會在 Zuul 中進(jìn)行處理,Zuul 中沒有自帶限流的功能,我們可以自己做限流或者集成第三方開源的限流框架。最新...

    jifei 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<