美文网首页
23. Spring Cloud Alibaba之服务容错组件

23. Spring Cloud Alibaba之服务容错组件

作者: Zal哥哥 | 来源:发表于2020-10-03 12:27 被阅读0次

    Sentinel使用方式

    使用方式 对应依赖 使用方法
    编码方式 API try...catch...finally...
    注解方式 @SentinelResource blockHandler/fallback
    整合RestTemplate @SentinelRestTemplate blockHandler/fallback
    整合Feitn @FeignClient fallback/fallbackFactory

    其中 使用 API 编码方式,我们这里不做过多的讲解,有兴趣同学,可自行研究,我们就剩余三种方式进行详细说明。

    Sentinel API的使用

    在代码中如何使用Sentinel API,Sentinel主要有以下三个API:

    • SphU:添加需要让sentinel监控、保护的资源
    • Tracer:对业务异常进行统计(非 BlockException 异常)
    • ContextUtil:上下文工具类,通常用于标识调用来源

    示例代码如下:

    @GetMapping("/test-sentinel-api")
    public String testSentinelAPI(@RequestParam(required = false) String a) {
        String resourceName = "test-sentinel-api";
        // 这里不使用try-with-resources是因为Tracer.trace会统计不上异常
        Entry entry = null;
        try {
            // 定义一个sentinel保护的资源,名称为test-sentinel-api
            entry = SphU.entry(resourceName);
            // 标识对test-sentinel-api调用来源为test-origin(用于流控规则中“针对来源”的配置)
            ContextUtil.enter(resourceName, "test-origin");
            // 模拟执行被保护的业务逻辑耗时
            Thread.sleep(100);
            return a;
        } catch (BlockException e) {
            // 如果被保护的资源被限流或者降级了,就会抛出BlockException
            log.warn("资源被限流或降级了", e);
            return "资源被限流或降级了";
        } catch (InterruptedException e) {
            // 对业务异常进行统计
            Tracer.trace(e);
            return "发生InterruptedException";
        } finally {
            if (entry != null) {
                entry.exit();
            }
    
            ContextUtil.exit();
        }
    }
    
    

    对几个可能有疑惑的点说明一下:

    • 资源名:可任意填写,只要是唯一的即可,通常使用接口名
    • ContextUtil.enter:在该例子中,用于标识对test-sentinel-api的调用来源均为test-origin。例如使用postman或其他请求方式调用了该资源,其来源都会被标识为test-origin
    • Tracer.trace:降级规则中可以针对异常比例或异常数的阈值进行降级,而Sentinel只会对BlockException及其子类进行统计,其他异常不在统计范围,所以需要使用Tracer.trace手动统计。1.3.1 版本开始支持自动统计,将在下一小节进行介绍

    相关官方文档:

    链接:https://www.jianshu.com/p/15a4e17b1049

    相关文章

      网友评论

          本文标题:23. Spring Cloud Alibaba之服务容错组件

          本文链接:https://www.haomeiwen.com/subject/zhbrektx.html