SpringCloud版本:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
从Spring.factories中
org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\
org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration
@Configuration
public class HystrixCircuitBreakerConfiguration {
@Bean
public HystrixCommandAspect hystrixCommandAspect() {
//初始化HystrixCommandAspect
return new HystrixCommandAspect();
}
@Bean
public HystrixShutdownHook hystrixShutdownHook() {
return new HystrixShutdownHook();
}
@Bean
public HasFeatures hystrixFeature() {
return HasFeatures.namedFeatures(new NamedFeature("Hystrix", HystrixCommandAspect.class));
}
}
@Aspect
public class HystrixCommandAspect {
//AOP切点(带有HystrixCommand注解的方法)
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void hystrixCommandAnnotationPointcut() {
}
//AOP切点(带有HystrixCollapser注解的方法)
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")
public void hystrixCollapserAnnotationPointcut() {
}
@Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
Method method = getMethodFromTarget(joinPoint);
//如果方法中同时有HystrixCollapser和HystrixCommand将会报错
if (method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {throw new IllegalStateException("");}
//根据不同的注解(HystrixCommand和HystrixCollapser)获取不同的MetaHolderFactory
MetaHolderFactory metaHolderFactory = META_HOLDER_FACTORY_MAP.get(HystrixPointcutType.of(method));
// 创建metaHolder,其中包含了各种必要信息,如注解的方法包含的各种信息以及fallback方法的各种信息,下面有源码
MetaHolder metaHolder = metaHolderFactory.create(joinPoint);//详见注解一
//通过HystrixCommandFactory获取执行对象
HystrixInvokable invokable = HystrixCommandFactory.getInstance().create(metaHolder);//详见注解二
//获取执行模式
ExecutionType executionType = metaHolder.isCollapserAnnotationPresent() ?
metaHolder.getCollapserExecutionType() : metaHolder.getExecutionType();
Object result;
try {
if (!metaHolder.isObservable()) {
//开始执行具体的逻辑()
result = CommandExecutor.execute(invokable, executionType, metaHolder);//详见下一篇请求过程分析
} else {
result = executeObservable(invokable, executionType, metaHolder);
}
} catch (HystrixBadRequestException e) {
throw e.getCause() != null ? e.getCause() : e;
} catch (HystrixRuntimeException e) {
throw hystrixRuntimeExceptionToThrowable(metaHolder, e);
}
return result;
}
注解一
metaHolderFactory.create(joinPoint)(HytrixCommandAspect)public MetaHolder create(final ProceedingJoinPoint joinPoint) {
Method method = getMethodFromTarget(joinPoint);
Object obj = joinPoint.getTarget();
Object[] args = joinPoint.getArgs();
Object proxy = joinPoint.getThis();
return create(proxy, method, obj, args, joinPoint);
}
public abstract MetaHolder create(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint);
//CommandMetaHolderFactory对create方法进行了实现
private static class CommandMetaHolderFactory extends MetaHolderFactory {
@Override
public MetaHolder create(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
HystrixCommand hystrixCommand = method.getAnnotation(HystrixCommand.class);
//获取ExecutionType,包含种类: ASYNCHRONOUS(同步 )、OBSERVABLE(Rxjava)、SYNCHRONOUS(异步 )(默认);
ExecutionType executionType = ExecutionType.getExecutionType(method.getReturnType());
MetaHolder.Builder builder = metaHolderBuilder(proxy, method, obj, args, joinPoint);
if (isCompileWeaving()) {
builder.ajcMethod(getAjcMethodFromTarget(joinPoint));
}
return builder.defaultCommandKey(method.getName())
.hystrixCommand(hystrixCommand)
//ObservableExecutionMode:EAGER(Observable 会在被创建后立刻执行)、LAZY(则会产生一个 Observable 被 subscribe 后执行)
.observableExecutionMode(hystrixCommand.observableExecutionMode())
.executionType(executionType)
//执行方式:rxjava执行还是其他方式执行
.observable(ExecutionType.OBSERVABLE == executionType)
.build();
}
}
metaHolderBuilder(proxy, method, obj, args, joinPoint);调用父类的方法
(HystrixCommandAspect)MetaHolder.Builder metaHolderBuilder(Object proxy, Method method, Object obj, Object[] args, final ProceedingJoinPoint joinPoint) {
MetaHolder.Builder builder = MetaHolder.builder()
.args(args).method(method).obj(obj).proxyObj(proxy)
.joinPoint(joinPoint);
//设置服务降级的方法
setFallbackMethod(builder, obj.getClass(), method);
//设置defaultGroupKey、defaultThreadPoolKey
builder = setDefaultProperties(builder, obj.getClass(), joinPoint);
return builder;
}
注解二
HystrixInvokable invokable = HystrixCommandFactory.getInstance().create(metaHolder);
//根据注解和executionType来判断采用什么样的HystrixInvokable
public HystrixInvokable create(MetaHolder metaHolder) {
HystrixInvokable executable;
if (metaHolder.isCollapserAnnotationPresent()) {
executable = new CommandCollapser(metaHolder);
} else if (metaHolder.isObservable()) {
executable = new GenericObservableCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder));
} else {
executable = new GenericCommand(HystrixCommandBuilderFactory.getInstance().create(metaHolder));
}
return executable;
}
HystrixCommandBuilderFactory.getInstance().create(metaHolder)
public HystrixCommandBuilder create(MetaHolder metaHolder) {
return create(metaHolder, Collections.<HystrixCollapser.CollapsedRequest<Object, Object>>emptyList());
}
public <ResponseType> HystrixCommandBuilder create(MetaHolder metaHolder, Collection<HystrixCollapser.CollapsedRequest<ResponseType, Object>> collapsedRequests) {
validateMetaHolder(metaHolder);
return HystrixCommandBuilder.builder()
//builder中包含groupKey、threadPoolKey、commandKey等注解信息
.setterBuilder(createGenericSetterBuilder(metaHolder))
//构建commandAction,将具体调用的方法封装为commandAction,例:@HystrixCommand,包含commandAction和fallbackAction;commandAction为实际的请求逻辑。fallbackAction为服务降级之后的调用方法。
.commandActions(createCommandActions(metaHolder))
//builder中包含groupKey、threadPoolKey、commandKey等注解信息
.collapsedRequests(collapsedRequests)
//如果存在@CacheResult,对结果缓存的基础信息构建
.cacheResultInvocationContext(createCacheResultInvocationContext(metaHolder))
//如果存在@CacheRemove,对删除缓存的基础信息构建
.cacheRemoveInvocationContext(createCacheRemoveInvocationContext(metaHolder))
.ignoreExceptions(metaHolder.getCommandIgnoreExceptions())
.executionType(metaHolder.getExecutionType())
.build();
}
GenericCommand构造方法的执行;
public GenericCommand(HystrixCommandBuilder builder) { super(builder); } (AbstractHystrixCommand)protected AbstractHystrixCommand(HystrixCommandBuilder builder) { super(builder.getSetterBuilder().build()); this.commandActions = builder.getCommandActions(); this.collapsedRequests = builder.getCollapsedRequests(); this.cacheResultInvocationContext = builder.getCacheResultInvocationContext(); this.cacheRemoveInvocationContext = builder.getCacheRemoveInvocationContext(); this.ignoreExceptions = builder.getIgnoreExceptions(); this.executionType = builder.getExecutionType(); } (AbstractCommand)protected AbstractCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults, HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) { //初始化group,group主要是用来对不同的command key进行统一管理 this.commandGroup = initGroupKey(group); // 初始化command key,用来标识降级逻辑 this.commandKey = initCommandKey(key, getClass()); // 初始化自定义的降级策略 this.properties = initCommandProperties(this.commandKey, propertiesStrategy, commandPropertiesDefaults); // 初始化线程池key,相同的线程池key将公用线程池 this.threadPoolKey = initThreadPoolKey(threadPoolKey, this.commandGroup, this.properties.executionIsolationThreadPoolKeyOverride().get()); // 初始化监控器,里面会保存每个命令相关的执行信息 this.metrics = initMetrics(metrics, this.commandGroup, this.threadPoolKey, this.commandKey, this.properties); // 初始化断路器,控制着熔断器的开闭。 this.circuitBreaker = initCircuitBreaker(this.properties.circuitBreakerEnabled().get(), circuitBreaker, this.commandGroup, this.commandKey, this.properties, this.metrics); 初始化线程池 this.threadPool = initThreadPool(threadPool, this.threadPoolKey, threadPoolPropertiesDefaults); //Strategies from plugins this.eventNotifier = HystrixPlugins.getInstance().getEventNotifier(); this.concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(this.commandKey, this.commandGroup, this.metrics, this.circuitBreaker, this.properties); this.executionHook = initExecutionHook(executionHook); this.requestCache = HystrixRequestCache.getInstance(this.commandKey, this.concurrencyStrategy); this.currentRequestLog = initRequestLog(this.properties.requestLogEnabled().get(), this.concurrencyStrategy); /* fallback semaphore override if applicable */ this.fallbackSemaphoreOverride = fallbackSemaphore; /* execution semaphore override if applicable */ this.executionSemaphoreOverride = executionSemaphore; } initCircuitBreaker(this.properties.circuitBreakerEnabled().get(), circuitBreaker, this.commandGroup, this.commandKey, this.properties, this.metrics); 每一个command对应有一个HystrixCircuitBreaker,保存断路器的HashMap声明在HystrixCircuitBreaker.Factory中,key是Command key。 private static ConcurrentHashMap<String, HystrixCircuitBreaker> circuitBreakersByCommand = new ConcurrentHashMap<String, HystrixCircuitBreaker>();