SpringCloudAlibaba整合Sentinel

本文介绍了如何在SpringCloud应用中安装并使用Sentineljar包,包括依赖管理、yaml配置、流控策略(QPS和线程数)、异常统一处理以及规则的配置和测试过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装运行Sentinel的jar包

导入依赖
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

yaml配置

启动项目,访问任意接口即可

通过页面配置流控
    @RequestMapping("get")
    @SentinelResource(value = "get", blockHandler = "getBlockHandler")
    public String get() {
        return "hello sentinel";
    }

    public String getBlockHandler(BlockException e) {
        e.printStackTrace();
        return "流控";
    }
根据QPS配置流控

根据线程数流控

添加一个睡眠时间,方便测试

配置规则

统一异常处理
@Data
public class Result<T> {
    private Integer code;

    private String msg;

    private T data;

    public Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static Result error(Integer code, String msg) {
        return new Result(code, msg);
    }
}
@Slf4j
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(
            HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e
    ) throws Exception {
        log.info("BlockExceptionHandler BlockException========{}", e.getRule());

        Result r = null;

        if (e instanceof FlowException) {
            r = Result.error(100, "接口限流了");
        } else if (e instanceof DegradeException) {
            r = Result.error(101, "服务降级了");
        } else if (e instanceof ParamFlowException) {
            r = Result.error(102, "热点参数限流了");
        } else if (e instanceof SystemBlockException) {
            r = Result.error(103, "触发系统保护规则了");
        } else if (e instanceof AuthorityException) {
            r = Result.error(104, "授权规则不通过");
        }

        //  返回Json数据
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), r);
    }
}

注释掉注解,测试是否配置成功

重启后配置流控规则,然后测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值