@EnableHystrix
开关
@EnableCircuitBreaker
public @interface EnableHystrix {
}
// EnableCircuitBreaker 通过import打开开关
@Import(EnableCircuitBreakerImportSelector.class)
public @interface EnableCircuitBreaker {
}
EnableCircuitBreakerImportSelector
是怎打开开关的,见下面代码; 关于选择器是怎么生效的,看我的博客spring boot自动配置
@Order(Ordered.LOWEST_PRECEDENCE - 100)
public class EnableCircuitBreakerImportSelector extends
SpringFactoryImportSelector<EnableCircuitBreaker> {
// 这里就是断路器开关,默认返回true; isEnabled会在父类中被调用
@Override
protected boolean isEnabled() {
return getEnvironment().getProperty(
"spring.cloud.circuit.breaker.enabled", Boolean.class, Boolean.TRUE);
}
}
SpringFactoryImportSelector
中是怎么让开关生效的
@Override
public String[] selectImports(AnnotationMetadata metadata) {
// org.springframework.cloud.client.circuitbreaker.EnableCircuitBreakerImportSelector#isEnabled 方法
// 返回true, 所以if走不进来,会继续往下执行
if (!isEnabled()) {
return new String[0];
}
AnnotationAttributes attributes = AnnotationAttributes.fromMap(
metadata.getAnnotationAttributes(this.annotationClass.getName(), true));
Assert.notNull(attributes, "No " + getSimpleName() + " attributes found. Is "
+ metadata.getClassName() + " annotated with @" + getSimpleName() + "?");
// Find all possible auto configuration classes, filtering duplicates
// 这里会查找配置类,
List<String> factories = new ArrayList<>(new LinkedHashSet<>(SpringFactoriesLoader
.loadFactoryNames(this.annotationClass, this.beanClassLoader)));
if (factories.isEmpty() && !hasDefaultFactory()) {
throw new IllegalStateException("Annotation @" + getSimpleName()
+ " found, but there are no implementations. Did you forget to include a starter?");
}
if (factories.size() > 1) {
// there should only ever be one DiscoveryClient, but there might be more than
// one factory
log.warn("More than one implementation " + "of @" + getSimpleName()
+ " (now relying on @Conditionals to pick one): " + factories);
}
return factories.toArray(new String[factories.size()]);
}
hystrix开关打开后会加载spring.factories文件中下面的hystrix配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.netflix.hystrix.HystrixAutoConfiguration,\
org.springframework.cloud.netflix.hystrix.security.HystrixSecurityAutoConfiguration
org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\
org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration