当前位置:网站首页>Sentinel source code analysis Part 8 - core process - sphu Entry current limiting execution
Sentinel source code analysis Part 8 - core process - sphu Entry current limiting execution
2022-06-30 01:11:00 【Age man】
List of articles
Use
ContextUtil.enter May or may not call
When to call reasonable ? If you don't care EntranceNode, Use and share EntranceNode There is no need to call , It will be built internally
If you want to EntranceNode As far as the resource dimension is concerned, it is called externally , It will be based on the transmitted resources name structure EntranceNode,[ The premise is that at present Context There is no such thing as ]
- Show build context
- SphU perform
Show build context
ContextUtil.enter(name, origin);
SphU perform
interfaceEntry = SphU.entry(interfaceResourceName, ResourceTypeConstants.COMMON_RPC, EntryType.IN);
- remarks : SphU meaning ? 2021 In, the author searched for the last time SphU The Chinese meaning of , No results ; If there are students who know , Welcome to let me know , thank !
Source code analysis one ContextUtil.enter
- First from ThreadLocal In order to get , There is a direct return to
- If the number of resources is greater than the maximum threshold Set and return NULL_CONTEXT【 Explain later 】
- structure Context
- Build... By name EntranceNode
- Set up Context To contextHolder
- Set up EntranceNode To contextNameNodeMap
- Set up Context Of entranceNode
- Set up Constants.ROOT Child nodes of EntranceNode
public class ContextUtil {
public static Context enter(String name, String origin) {
...... Delete other codes
return trueEnter(name, origin);
}
/** * * 1. First from ThreadLocal In order to get , If you can get it, return it directly , If not, continue with the second 2 Step * 2. From a static Of map According to the name of the context , If it can be obtained, it will directly return to , Otherwise, continue with the second step 3 Step * 3. Once after locking double check, If you still can't get from map Get to the , Then create a EntranceNode, And put the EntranceNode Add to a global ROOT In the child nodes of the node , Then add the node to map In the middle ( This part of the code is omitted in the above code ) * 4. according to EntranceNode Create a context , And save the context to ThreadLocal In the middle , The next request can be obtained directly * remarks 1: EntranceNode Based on the incoming name structure * remarks 2: There is no outside Context Then use here to create an internal Context */
protected static Context trueEnter(String name, String origin) {
context Is stored in the ThreadLocal Medium , Every time it is executed, it takes precedence to ThreadLocal In order to get . If context by null Will create one again context.
/** * in other words entry It is a link relationship * * context Will be set to null And from ThreadLocal Middle empty The timing of * When Entry perform exit When the method is used , When the present entry Of parent by null when , It means that at present entry It is the top node * At this point, save in ThreadLocal Medium context Also empty * * */
Context context = contextHolder.get();
if (context == null) {
If ThreadLocal Can't get Context
According to name from map In order to get entranceNode, As long as it's the same resource name , You can go straight from map Get to the node
Map<String/*contextName*/, DefaultNode/*entranceNode*/> localCacheNameMap = contextNameNodeMap;
DefaultNode node = localCacheNameMap.get(name);
if (node == null) {
If the number of resources is greater than the maximum threshold Then return to NULL_CONTEXT
if (localCacheNameMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
setNullContext();
return NULL_CONTEXT;
} else {
LOCK.lock();
try {
node = contextNameNodeMap.get(name);
if (node == null) {
if (contextNameNodeMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
setNullContext();
return NULL_CONTEXT;
} else {
add to entranceNode To Root node
node = new EntranceNode(new StringResourceWrapper(name, EntryType.IN), null);
// Add entrance node.
Constants.ROOT.addChild(node);
/** * Tips : * newly build node Write cache map * In order to prevent " Iterative stability problem " iterate stable For the write operation of the shared collection, use COW * */
Map<String, DefaultNode> newMap = new HashMap<>(contextNameNodeMap.size() + 1);
newMap.putAll(contextNameNodeMap);
newMap.put(name, node);
contextNameNodeMap = newMap;
}
}
} finally {
LOCK.unlock();
}
}
}
Same thread Of the same resource EntranceNode It must be the same
context = new Context(node, name);
context.setOrigin(origin);
contextHolder.set(context);
}
return context;
}
}
Source code analysis one SphU.entry
- call CtSph Carry out current limiting
public class SphU {
public static Entry entry(String name, int resourceType, EntryType trafficType) throws BlockException {
batchCount Indicates how much the current request traffic has increased such as http qps One request to add 1
return Env.sph.entryWithType(name, resourceType, trafficType, 1, OBJECTS0);
}
}
public class CtSph implements Sph {
@Override
public Entry entryWithType(String name, int resourceType, EntryType entryType, int count, Object[] args)
throws BlockException {
No priority processing is required
return entryWithType(name, resourceType, entryType, count, false, args);
}
public Entry entryWithType(String name, int resourceType, EntryType entryType, int count, boolean prioritized,
Object[] args) throws BlockException {
Building resource objects
StringResourceWrapper resource = new StringResourceWrapper(name, entryType, resourceType);
return Entry Link object prioritized Represents the resource operation object with priority
false Indicates that the current access does not need to wait for a certain time true Indicates that the current access must wait for a certain period of time 【 Calculate the waiting time according to the priority 】
return entryWithPriority(resource, count, prioritized, args);
}
}
Source code analysis one CtSph.entryWithPriority
- Protect yourself [EntranceNode The quantity corresponds to NullContext and chainMap Quantity detection ]
- Whether the global switch allows sentinel Work
- Find the work chain corresponding to the resource ProcessorSlotChain
- structure Entry The current node of the linked list stack CtEntry
- chain.entry complete sentinel Core working logic , Cluster link , Data statistics , Rule detection, etc
- Throw an exception if current limit occurs
- If no current limit occurs, it returns CtEntry
private Entry entryWithPriority(ResourceWrapper resourceWrapper, int count, boolean prioritized, Object... args)
throws BlockException {
Check parameters and global configuration items , If it does not meet the requirements, it directly returns a CtEntry object , There will be no further current limiting detection , Otherwise, enter the following detection process
Context context = ContextUtil.getContext();
if (context instanceof NullContext) {
When the context exceeds the number Directly return one entry Not in progress 【 Current limiting 】 Rule checking Self-protection mechanism
return new CtEntry(resourceWrapper, null, context);
}
if (context == null) {
At present ThreadLocal There is no rule in the Use default context and default EntranceNode
context = InternalContextUtil.internalEnter(Constants.CONTEXT_DEFAULT_NAME);
}
if (!Constants.ON) {
If the global switch is turned off, it will not be carried out 【 Current limiting, degradation, etc 】 Rule checking
return new CtEntry(resourceWrapper, null, context);
}
Get the corresponding SlotChain[ Linked list , Responsibility chain ]
Get the corresponding... According to the wrapped resource object SlotChain 【 That is, each rule handles Slot】
ProcessorSlot<Object> chain = lookProcessChain(resourceWrapper);
/* * Means amount of resources (slot chain) exceeds {@link Constants.MAX_SLOT_CHAIN_SIZE}, * so no rule checking will be done. */
It's generating chain There is a judgment in , If chainMap.size If it is greater than the threshold, it returns null【 signify chain The number of exceeds the upper limit 】, No rule detection
if (chain == null) {
return new CtEntry(resourceWrapper, null, context);
}
perform SlotChain Of entry Method
If SlotChain Of entry Method throws BlockException Current limiting occurs , Continue to throw the exception upward
If SlotChain Of entry The method is executed normally , In the end, it will entry Object returns
Current limiting core establish entry Determine whether current limiting is needed
Entry e = new CtEntry(resourceWrapper, chain, context);
try {
Start the inspection rule
/** * * * Every ProcessorSlot Of entry() Method is responsible for the real business processing part * * NodeSelectorSlot The path responsible for collecting resources , And the call path of these resources , Store in a tree structure , It is used to limit current and degrade according to the calling path ; * ClusterBuilderSlot It is used to store resource statistics and caller information , For example, the RT, QPS, thread count wait , This information will be used as multi-dimensional flow limiting , The basis of the downgrade ; * StatistcSlot To record , Count... At different latitudes runtime Information ; * * * FlowSlot It is used according to the preset current limiting rules , And the front slot The state of Statistics , To limit the flow ; * AuthorizationSlot According to the black and white list , To do black and white list control ; * DegradeSlot Through statistics , And the default rules , To do the fusing degradation ; * SystemSlot Through the state of the system , for example load1 etc. , To control the total inlet flow ; * * */
chain.entry(context, resourceWrapper, null, count, prioritized, args);
} catch (BlockException e1) {
Current limiting , Throw it up , here exit 了 , And the outside world finally It needs to be judged empty and then exit
e.exit(count, args);
throw e1;
} catch (Throwable e1) {
Defensive programming Used to handle exceptions
This should not happen, unless there are errors existing in Sentinel internal. RecordLog.info("Sentinel unexpected exception", e1);
}
return e;
}
summary
- 【 Self protection 】 If at present EntranceNode More than have been built 2000 Then return to NullContext
- When SphU.entry The execution discovery is NullContext Then the current limiting logic will not be executed
- This is a sentinel A self-protection mechanism , prevent EntranceNode Too much
- It is also impossible to build a project in a general microservice scenario 2000 individual EntranceNode
- EntranceNode The construction of is independent of the definition of flow restriction rules , As long as the traffic accesses the relevant Adapter Modules build
- 【 Self protection 】 If chainMap exceed 6000, Description yes 6000 Resource mount , Then current limiting is not implemented
边栏推荐
- How does webapi relate to the database of MS SQL?
- 我,33岁,字节跳动测试开发,揭开北京“测试岗”的真实收入
- Lower expectations
- Shell spec date format
- 如何查看一个文件夹下所有文件的大小?
- 利用tsne将不同句子关于相似度可视化出来
- VIM editor common instructions
- STC89C52 single chip microcomputer simple calculator design and code demonstration
- Reading is the cheapest noble
- Common settings in idea
猜你喜欢

3-6sql injection website instance step 5: break through the background to obtain web administrator permissions

Interviewer: how to solve the problem of massive requests for data that does not exist in redis, which affects the database?

Clean, talk, bring children, and get rid of the label of "artificial mental retardation" for the sweeper

2022 6 月25 日交易总结

How to switch to root in xshell
![[mrctf2020]ezpop-1 | PHP serialization](/img/f8/6164b4123e0d1f3b90980ebb7b4097.png)
[mrctf2020]ezpop-1 | PHP serialization

Analysis of IM instant messaging development technology on modern web

眼底出血术后需注意事项//每天必看

In depth analysis of a large number of clos on the server_ The root of wait

Crmeb SMS for program configuration of knowledge payment system
随机推荐
Transaction summary on June 25, 2022
利用huggingface进行文本分类
How to seamlessly transition from traditional microservice framework to service grid ASM
How to view the size of all files in a folder?
Good test / development programmers vs. average programmers
Wechat applet - requestsubscribemessage:fail can only be invoked by user tap gesture
Simple pages
Solving plane stress problem with MATLAB
VIM编辑器常用指令
Analysis of natural frequency and buckling load of cylinder by finite element method
After the element uses align items center and overflow auto, some contents are not fully displayed
In 2022, the latest and most detailed idea associated database method and visual operation of database in idea (including graphic process)
Solve the problem of repairing Visual Basic exceptions with excel/wps plug-in of choice financial terminal
Visual studio 2017 cannot open the include file: 'qopenglfunctions_3_3_core': no such file or directory
在线SQL转CSV工具
2022 6 月25 日交易总结
How latex enters a matrix
Newton method (optimization of two variable functions)
numpy的索引和图片的索引一样吗?
Text classification using huggingface