一、sentinel简介:
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。伴随着公司用户量和流量的日益增加,对于数据库的压力是越来越大,Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护
二、源码入口
使用sentinel有两种方式,一种方式是对需要限流和降级的接口资源方法上面加入@SentinelResource注解
还有一种就是通过拦截器的方式进行资源保护限流和降级,其实两种方法执行的关键方法都是同一段代码,今天我们就讲 一下通过注解这种aop切面的形式,sentinel是如何实现限流和降级的呢
源码的如何还是基于SpringBoot的自动装配原理,在spring-cloud-starter-alibaba-sentinel.jar
下面的spring.fatories里面的SentinelAutoConfiguration类,我们来看看这个类的源码
在spring容器启动的时候实例化了一个SentinelResourceAspect类,看这个类的命名就应该可以猜到这个类就是一个切面类,我们点击进入
/**
-
Aspect for methods with {@link SentinelResource} annotation.
-
@author Eric Zhao
*/
@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 {
Method originMethod = resolveMethod(pjp);SentinelResource annotation = originMethod.getAnnotation(SentinelResource.class); if (annotation == null) { // Should not go through here. throw new IllegalStateException("Wrong state for SentinelResource annotation"); } String resourceName = getResourceName(annotation.value(), originMethod); EntryType entryType = annotation.entryType(); int resourceType = annotation.resourceType(); 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) { Class<? extends Throwable>[] exceptionsToIgnore = an