寻找一把进入 Alibaba Sentinel 的钥匙(文末附流程图)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

寻找一把进入 Alibaba Sentinel 的钥匙(文末附流程图)

中间件兴趣圈   2020-04-02 我要评论
经过前面几篇文章的铺垫,我们正式来探讨 Sentinel 的 entry 方法的实现流程。即探究进入 Alibaba Sentinel 核心的一把钥匙。 @[TOC](本节目录) 无论是从 Sentinel 适配 Dubbo 也好,还是 SphU 源码中的注释中能看出,对一个资源进行限流或熔断,通常需要调用 SphU 的 entry 方法,例如如下示例代码。 ~~~java public void foo() { Entry entry = null; try { entry = SphU.entry("abc"); } catch (BlockException blockException) { // when goes there, it is blocked // add blocked handle logic here } catch (Throwable bizException) { // business exception Tracer.trace(bizException); } finally { // ensure finally be executed if (entry != null){ entry.exit(); } } } ~~~ 那本文将来探讨 SphU.entry 的实现原理。SphU 类定义了很多 entry 重载方法,我们就以下面这个方法为例来探究其实现原理。 ## 1、SphU.entry 流程分析 ~~~java public static Entry entry(String name, EntryType type, int count, Object... args) throws BlockException { // @1 return Env.sph.entry(name, type, count, args); // @2 } ~~~ 代码@1:我们先来简单介绍其核心参数的含义: - String name 资源的名称。 - EntryType type 进入资源的方式,主要包含 EntryType.IN、EntryType.OUT。 - int count 可以理解为本次进入需要消耗的“令牌数”。 - Object... args 其他参数。 代码@2:调用 Env.sph.entry 的方法,其最终会调用 CtSph 的 entry 方法。 接下来我们将重点查看 CtSph 的 entry 方法。 ~~~java public Entry entry(String name, EntryType type, int count, Object... args) throws BlockException { StringResourceWrapper resource = new StringResourceWrapper(name, type); // @1 return entry(resource, count, args); // @2 } ~~~ 代码@1:由于该方法用来表示资源的方式为一个字符串,故创建一个 StringResourceWrapper 对象来表示一个 Sentinel 中的资源,另外一个实现为 MethodResourceWrapper,用来表示方法类的资源。 代码@2:继续调用 CtSph 的另外一个 entry 重载方法,最终会调用 entryWithPriority 方法。 CtSph#entryWithPriority ~~~java private Entry entryWithPriority(ResourceWrapper resourceWrapper, int count, boolean prioritized, Object... args) // @1 throws BlockException { Context context = ContextUtil.getContext(); // @2 if (context instanceof NullContext) { return new CtEntry(resourceWrapper, null, context); } if (context == null) { // Using default context. context = InternalContextUtil.internalEnter(Constants.CONTEXT_DEFAULT_NAME); } if (!Constants.ON) { // @3 return new CtEntry(resourceWrapper, null, context); } ProcessorSlot

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们