栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

gateway整合sentinel实现服务流控熔断降级

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

gateway整合sentinel实现服务流控熔断降级

1.在gateway服务模块中添加gateway整合sentinel的依赖


    com.alibaba.cloud
    spring-cloud-alibaba-sentinel-gateway




    com.alibaba.cloud
    spring-cloud-starter-alibaba-sentinel

2. 在application.yml配置文件中添加sentinel控制台的配置

sentinel:  #sentinel的配置
  transport:
    dashboard: localhost:8080  #配置sentinel dashboard地址
    port:  8719   #默认端口8719

3. 编写gateway配置类,自定义限流配置

package com.mc.tutor.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;

import com.mc.tutor.common.ResponseResult;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;


import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;


@Configuration
public class GatewayConfig {

    
    @PostConstruct
    public void init() {

        initCustomizedApis();

        initBlockHandler();
    }

    
    private void initCustomizedApis() {
        Set definitions = new HashSet<>();
        ApiDefinition api = new ApiDefinition("user-center")
                .setPredicateItems(new HashSet() {{
                    add(new ApiPathPredicateItem().setPattern("/user-center
    private void initBlockHandler() {
        BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) ->
                ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(ResponseResult.sendFailMsg("您的请求过于频繁,请稍后再试!")));

        // 加载自定义的限流异常处理器
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/584860.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号