Sentinel 是什么?github描述如下
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
本文建立在会使用Sentinel的基础上,详细的介绍和使用不会展开,具体介绍和使用看:Sentinel介绍
一个简单的Demo如下:
String resourceName = "资源名称";
Entry entry = null;
try {
entry = SphU.entry(resourceName);
run();
} catch (BlockException ex) {
throw ex;
} catch (Throwable ex) {
Tracer.trace(ex);
throw ex;
} finally {
if (entry != null) {
entry.exit();
}
}
这就是一个设置之后,run方法就会被Sentinel所监控起来,但是这时候,是没有任何效果的,因为没有告诉Sentinel需要去限制什么?在Sentinel中,这个叫做规则,即你需要设置好限制的规则,Sentinel会根据设置的规则去限制你的代码,即上面的run方法,那么下面来看下Sentinel的整个调用流程是如何。
以SphU.entry
方法为入口,一步步的跟进去
public static Entry entry(String name) throws BlockException {
return Env.sph.entry(name, EntryType.OUT, 1, OBJECTS0);// 1
}
//CtSph.java
public Entry entry(String name, EntryType type, int count, Object... args) throws BlockException {
StringResourceWrapper resource = new StringResourceWrapper(name, type);//2
return entry(resource, count, args);//3
}
- 1:entry有很多重载的方法,如果不填,就会设置默认值,其他参数后续分析
- 2:对于Sentinel来说,限制的是资源,这里将名称和EntryType构造成一个资源对象
- 3:接着调用entry方法进行处理
public Entry entry(ResourceWrapper resourceWrapper, int count, Object... args) throws BlockException {
return entryWithPriority(resourceWrapper, count, false, args);
}
private Entry entryWithPriority(ResourceWrapper resourceWrapper, int count, boolean prioritized, Object... args)
throws BlockException {
Context context = ContextUtil.getContext();// 1
if (context instanceof NullContext) {
return new CtEntry(resourceWrapper, null, context);
}
if (context == null) {
context = MyContextUtil.myEnter(Constants.CONTEXT_DEFAULT_NAME, "", resourceWrapper.getType());//2
}
if (!Constants.ON) {
//3
return new CtEntry(resourceWrapper, null, context);
}
ProcessorSlot<Object> chain = lookProcessChain(resourceWrapper);//4
/*
* Means amount of resources (slot chain) exceeds {@link Constants.MAX_SLOT_CHAIN_SIZE},
* so no rule checking will be done.
*/
if (chain == null) {
// 5
return new CtEntry(resourceWrapper, null, context);
}
Entry e = new CtEntry(resourceWrapper, chain, context);
try {
chain.entry(context, resourceWrapper, null, count, prioritized, args);//6
} catch (BlockException e1) {
e.exit(count, args);
throw e1;
} c