微服务自动装配
在微服务的使用Sentinel实际工作场景中,我们只需要引入对应依赖:spring-cloud-starter-alibaba-sentinel,就能使用流控了, 原因是引入后利用SpringBoot自动装配功能,所以在META-INF/spring.factories中有SentinelAutoConfiguration来实现流控Sentinel的自动装配。
SentinelAutoConfiguration
自动装配类中有如下代码自动注入Bean SentinelResourceAspect
public class SentinelAutoConfiguration {
...
@Bean
@ConditionalOnMissingBean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
...
}
SentinelResourceAspect
从代码可以看出SentinelResourceAspect是一个切面,那这个切面切了什么东西呢? 我们上源码看看
@Aspect
public class SentinelResourceAspect extends AbstractSentinelAspectSupport {
@Pointcut("@annotation(com.alibaba.csp.sentinel.annotation.SentinelResource)")
public void sentinelResourceAnnotationPointcut() {
}
@Around("sentinelResourceAnnotationPointcut()")
public Object invokeResourceWithSentinel(ProceedingJoinPoint pjp) throws Throwable {
..
Entry entry = null;
try {
entry = SphU.entry(resourceName, resourceType, entryType, pjp.getArgs());
Object result = pjp.proceed();
return result;
} catch (BlockException ex) {
return handleBlockException(pjp, annotation, ex);
} catch (Throwable ex) {
...
throw ex;
} finally {
if (entry != null) {
entry.exit(1, pjp.getArgs());
}
}
}
}
通过源码可以看出,通过对SentinelResource主键注释的方法的切入,然后调用在调用方法前执行相关的流控代码,这部分流控代码就和我们之前写的核心入口代码几乎一样,从而说明了SpringBoot项目中的流控入口代码。
在以上代码中并没有初始化创建Context上下文,之前说过,如果程序中未指定Context,会创建name为"sentinel_default_context"的默认Context,所以后续会使用默认的Context。