sentinel context组件源码分析

前言Context组件在sentinel中扮演的是一种什么样的角色呢?借用原作者的注释:This class holds metadata of current invocation其实就是保存一次资源访问链路元数据的类,链路的各个节点都能通过获取链路绑定的context来获取一些信息进行相应的处理。很多涉及链路的框架都会有类似设计,例如netty的ChannelHandlerConte...
摘要由CSDN通过智能技术生成

前言

Context组件在sentinel中扮演的是一种什么样的角色呢?借用原作者的注释:

This class holds metadata of current invocation

其实就是保存一次资源访问链路元数据的类,链路的各个节点都能通过获取链路绑定的context来获取一些信息进行相应的处理。很多涉及链路的框架都会有类似设计,例如netty的ChannelHandlerContext,go语言网络包中的context等等。下面通过源码分析sentinel中Context的创建和使用流程。


Context结构

com.alibaba.csp.sentinel.context.Context

public class Context {
   

    /**
     * Context name.
     */
    private final String name;

    /**
     * The entrance node of current invocation tree.
     */
    private DefaultNode entranceNode;

    /**
     * Current processing entry.
     */
    private Entry curEntry;

    /**
     * The origin of this context (usually indicate different invokers, e.g. service consumer name or origin IP).
     */
    private String origin = "";

    private final boolean async;

    ...

Context类主要由五个成员变量组成,分别是

  • name,一般是访问的资源名
  • entranceNode,就是记录当次链路流控信号量的node
  • curEntry,当前Context所属的entry
  • origin, 资源访问者信息
  • async,是否异步

Context创建

Context通常通过ContextUtil的enter方法创建,我们可以先看下ContextUtil类的源码
com.alibaba.csp.sentinel.context.ContextUtil

public class ContextUtil {
   

    /**
     * Store the context in ThreadLocal for easy access.
     */
    private static ThreadLocal<Context> contextHolder = new ThreadLocal<>();

    /**
     * Holds all {@link EntranceNode}. Each {@link EntranceNode} is associated with a distinct context name.
     */
    private static volatile Map<String, DefaultNode> contextNameNodeMap = new HashMap<>();

    private static final ReentrantLock LOCK = new ReentrantLock();
    private static final Context NULL_CONTEXT = new NullContext();

    static {
   
        // Cache the entrance node for default context.
        initDefaultContext();
    }

    private static void initDefaultContext() {
   
        String defaultContextName = Constants.CONTEXT_DEFAULT_NAME;
        EntranceNode node = new EntranceNode(new Str
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值