【SpringCloud-Alibaba系列教程】11.gateway與sentinel組合

引入問(wèn)題

在之前,我們教程已經(jīng)寫了一部分關(guān)于sentinel限流的方式,主要是針對(duì)于某個(gè)微服務(wù)本身進(jìn)行限流,后來(lái)我們引入網(wǎng)關(guān)的概念,現(xiàn)在我們結(jié)合gateway與sentinel進(jìn)行限流,主要是從一下兩個(gè)緯度,第一個(gè)就是路由維度,另一種就是分組維度,下面我們根據(jù)不同維度進(jìn)行實(shí)戰(zhàn)。

我們開(kāi)始吧
首先引入pom相關(guān)文件

  <!--網(wǎng)關(guān)路由限流-->

       <dependency>

           <groupId>com.alibaba.csp</groupId>

           <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>

       </dependency>

然后編寫相關(guān)配置類


image.png

我們是基于sentinel的所以我們需要初始化這樣一個(gè)。

//初始化限流過(guò)濾器
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() {
    return new SentinelGatewayFilter();
}

然后就是編寫配置類了


image.png

我們多次刷新就可以看到了


image.png

另外一個(gè)就是分組限流,主要就是通過(guò)將不同的api進(jìn)行分組,指定一些接口限流。
直接上代碼

/**
 * 配置限流規(guī)則
 */
@PostConstruct
private void initGatewayRules() {
    //Set<GatewayFlowRule> rules = new HashSet<>();
    //rules.add(new GatewayFlowRule("product_route")//資源名稱對(duì)應(yīng)的路由id
    //        .setCount(1) // 限流閾值
    //        .setIntervalSec(1) // 統(tǒng)計(jì)時(shí)間窗口,單位是秒,默認(rèn)是 1 秒
    //);
    //GatewayRuleManager.loadRules(rules);
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("product_api1").setCount(1).setIntervalSec(1));
    rules.add(new GatewayFlowRule("product_api2").setCount(1).setIntervalSec(1));
    GatewayRuleManager.loadRules(rules);
}
//配置限流的異常處理器
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
    // Register the block exception handler for Spring Cloud Gateway.
    return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
}
//自定義限流異常頁(yè)面
@PostConstruct
public void initBlockHandlers() {
    BlockRequestHandler blockRequestHandler = new BlockRequestHandler(){
        @Override
        public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
            Map map = new HashMap();
            map.put("code",0);
            map.put("messgae","接口被限流了...");
            return  ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).
                    body(BodyInserters.fromObject(map));
        }
    };
    GatewayCallbackManager.setBlockHandler(blockRequestHandler);
}
//自定義API分組
@PostConstruct
private void initCustomizedApis() {
    Set<ApiDefinition> definitions = new HashSet<>();
    ApiDefinition api1 = new ApiDefinition("product_api1")
            .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                ///product-serv/product/api1開(kāi)頭的請(qǐng)求
                add(new ApiPathPredicateItem().setPattern("/product-serv/product/api1/**")
                        .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
            }});
    ApiDefinition api2 = new ApiDefinition("product_api2")
            .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                ///product-serv/product/api2
                add(new ApiPathPredicateItem().setPattern("/product-serv/product/api2/demo1"));
            }});
    definitions.add(api1);
    definitions.add(api2);
    GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}

主要就是這樣的兩種方式進(jìn)行限流。
到此,我們這一章的sentinel與gateway組合就完成了
后期會(huì)在這個(gè)項(xiàng)目上不斷添加,喜歡的請(qǐng)點(diǎn)個(gè)start~
項(xiàng)目源碼參考一下分支220212_xgc_gatewayAndSentinel
Gitee:https://gitee.com/coderxgc/springcloud-alibaba
GitHub:https://github.com/coderxgc/springcloud-alibaba

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容