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

2020-10-03  本文已影响0人  Zal哥哥

Sentinel使用方式

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

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

Sentinel API的使用

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

示例代码如下:

@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();
    }
}

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

相关官方文档:

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

上一篇下一篇

猜你喜欢

热点阅读