这是我参与8月更文挑战的第3天,活动详情查看:8月更文挑战
首先分享之前的所有文章 , 欢迎点赞收藏转发三连下次一定 >>>> 😜😜😜
文章合集 : 🎁 juejin.cn/post/694164…
Github : 👉 github.com/black-ant
CASE 备份 : 👉 gitee.com/antblack/ca…
一 . 前言
文章目的
- 梳理 Sentinel 的集成方式
- 深入 Sentinel 的集成原理
二 . 使用教程
使用共分为2步 : 构建规则和传输实体
2.1 构建规则
1 | java复制代码public void buildRule(String resourceName) { |
2.2 使用流程
1 | java复制代码public String flowControlSync(Integer qpsNum) { |
三 . 深入源码
3.1 FlowRuleManager 加载 rules
在2.1 中通过 FlowRuleManager 构建了一个 Rule :
- 创建 FlowRule 对象
- 为 Rule 设置资源
- 设置限流的策略
- FlowRuleManager.loadRules 加载规则
这里来详细看一下 Rules 的处理逻辑 :
Step 1 : 加载资源 , 这里可以看到是放在了 SentinelProperty 里面
1 | java复制代码private static SentinelProperty<List<FlowRule>> currentProperty = |
Step 2 : PropertyListener 监听配置改变
当配置完成后 , 会通知 PropertyListener 相关配置已经改变 , 先来看一下 PropertyListener 体系
1 | java复制代码private static final Map<String, List<FlowRule>> flowRules = new ConcurrentHashMap<String, List<FlowRule>>(); |
最终可以得到如下的对象 :
至此配置部分就完成了 , 下面来看一下拦截的部分 >>>
3.2 执行流程
在这个部分有2个主要的对象 : Entry + SphU
Step 1 : 发起处理请求
1 | java复制代码// SphU.entry("FlowControl") |
Step 2 : 逻辑判断
1 | java复制代码private Entry entryWithPriority(ResourceWrapper resourceWrapper, int count, boolean prioritized, Object... args) |
补充 : resourceWrapper
Step 2-1 : 初始化 Context
1 | java复制代码protected static Context trueEnter(String name, String origin) { |
Step 2-1 : lookProcessChain 获取 Slot 链
1 | java复制代码ProcessorSlot<Object> lookProcessChain(ResourceWrapper resourceWrapper) { |
Step 3 : DefaultProcessorSlotChain 处理
调用流程如下 :
- C- SphU # entry
- C- CtSph # entry
- C- CtSph # entryWithPriority
- C- DefaultProcessorSlotChain # entry
- C- AbstractLinkedProcessorSlot # transformEntry
- C- DefaultProcessorSlotChain # entry
- C- AbstractLinkedProcessorSlot # fireEntry
1 | java复制代码public void entry(Context context, ResourceWrapper resourceWrapper, Object t, int count, boolean prioritized, Object... args) |
可以看到这里会分别执行多个 slot ,TODO 具体的 slot 下回分析
Step 4 : FlowSlot 的处理
这里我们只关注流程 , 下一篇再过一遍 slot , 限流的判断逻辑在 FlowSlot 中 :
1 | JAVA复制代码C- FlowSlot |
四 . 容器的处理
4.1 构建 ContextUtil
Step 1 : Context 的存储
1 | java复制代码public class ContextUtil { |
Step 2 : Context 的清除
1 | java复制代码public static void exit() { |
总结
作为 sentinel 的开篇 ,比较简单 , 主要是过流程
本文转载自: 掘金