文档章节

聊聊spring cloud的HystrixCircuitBreakerConfiguration

go4it
 go4it
发布于 06/24 00:53
字数 756
阅读 15
收藏 2
点赞 0
评论 0

本文主要研究一下spring cloud的HystrixCircuitBreakerConfiguration

HystrixCircuitBreakerConfiguration

spring-cloud-netflix-core-2.0.0.RELEASE-sources.jar!/org/springframework/cloud/netflix/hystrix/HystrixCircuitBreakerConfiguration.java

@Configuration
public class HystrixCircuitBreakerConfiguration {

	@Bean
	public HystrixCommandAspect hystrixCommandAspect() {
		return new HystrixCommandAspect();
	}

	@Bean
	public HystrixShutdownHook hystrixShutdownHook() {
		return new HystrixShutdownHook();
	}

	@Bean
	public HasFeatures hystrixFeature() {
		return HasFeatures.namedFeatures(new NamedFeature("Hystrix", HystrixCommandAspect.class));
	}

	//FIXME: 2.0.0
	/*@Configuration
	@ConditionalOnProperty(value = "hystrix.metrics.enabled", matchIfMissing = true)
	@ConditionalOnClass({ HystrixMetricsPoller.class, GaugeService.class })
	@EnableConfigurationProperties(HystrixMetricsProperties.class)
	protected static class HystrixMetricsPollerConfiguration implements SmartLifecycle {

		private static Log logger = LogFactory
				.getLog(HystrixMetricsPollerConfiguration.class);

		@Autowired(required = false)
		private GaugeService gauges;

		@Autowired
		private HystrixMetricsProperties metricsProperties;

		private ObjectMapper mapper = new ObjectMapper();

		private HystrixMetricsPoller poller;

		private Set<String> reserved = new HashSet<String>(Arrays.asList("group", "name",
				"type", "currentTime"));

		@Override
		public void start() {
			if (this.gauges == null) {
				return;
			}
			MetricsAsJsonPollerListener listener = new MetricsAsJsonPollerListener() {
				@Override
				public void handleJsonMetric(String json) {
					try {
						@SuppressWarnings("unchecked")
						Map<String, Object> map = HystrixMetricsPollerConfiguration.this.mapper
								.readValue(json, Map.class);
						if (map != null && map.containsKey("type")) {
							addMetrics(map, "hystrix.");
						}
					}
					catch (IOException ex) {
						// ignore
					}
				}

			};
			this.poller = new HystrixMetricsPoller(listener,
					metricsProperties.getPollingIntervalMs());
			// start polling and it will write directly to the listener
			this.poller.start();
			logger.info("Starting poller");
		}

		private void addMetrics(Map<String, Object> map, String root) {
			StringBuilder prefixBuilder = new StringBuilder(root);
			if (map.containsKey("type")) {
				prefixBuilder.append((String) map.get("type"));
				if (map.containsKey("group")) {
					prefixBuilder.append(".").append(map.get("group"));
				}
				prefixBuilder.append(".").append(map.get("name"));
			}
			String prefix = prefixBuilder.toString();
			for (String key : map.keySet()) {
				Object value = map.get(key);
				if (!this.reserved.contains(key)) {
					if (value instanceof Number) {
						String name = prefix + "." + key;
						this.gauges.submit(name, ((Number) value).doubleValue());
					}
					else if (value instanceof Map) {
						@SuppressWarnings("unchecked")
						Map<String, Object> sub = (Map<String, Object>) value;
						addMetrics(sub, prefix);
					}
				}
			}
		}

		@Override
		public void stop() {
			if (this.poller != null) {
				this.poller.shutdown();
			}
		}

		@Override
		public boolean isRunning() {
			return this.poller != null ? this.poller.isRunning() : false;
		}

		@Override
		public int getPhase() {
			return Ordered.LOWEST_PRECEDENCE;
		}

		@Override
		public boolean isAutoStartup() {
			return true;
		}

		@Override
		public void stop(Runnable callback) {
			if (this.poller != null) {
				this.poller.shutdown();
			}
			callback.run();
		}

	}*/

	/**
	 * {@link DisposableBean} that makes sure that Hystrix internal state is cleared when
	 * {@link ApplicationContext} shuts down.
	 */
	private class HystrixShutdownHook implements DisposableBean {

		@Override
		public void destroy() throws Exception {
			// Just call Hystrix to reset thread pool etc.
			Hystrix.reset();
		}

	}

}

这里主要是创建了HystrixCommandAspect以及HystrixShutdownHook

HystrixCommandAspect

hystrix-javanica-1.5.12-sources.jar!/com/netflix/hystrix/contrib/javanica/aop/aspectj/HystrixCommandAspect.java

/**
 * AspectJ aspect to process methods which annotated with {@link HystrixCommand} annotation.
 */
@Aspect
public class HystrixCommandAspect {

    private static final Map<HystrixPointcutType, MetaHolderFactory> META_HOLDER_FACTORY_MAP;

    static {
        META_HOLDER_FACTORY_MAP = ImmutableMap.<HystrixPointcutType, MetaHolderFactory>builder()
                .put(HystrixPointcutType.COMMAND, new CommandMetaHolderFactory())
                .put(HystrixPointcutType.COLLAPSER, new CollapserMetaHolderFactory())
                .build();
    }

    @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")

    public void hystrixCommandAnnotationPointcut() {
    }

    @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);
        Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
        if (method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {
            throw new IllegalStateException("method cannot be annotated with HystrixCommand and HystrixCollapser " +
                    "annotations at the same time");
        }
        MetaHolderFactory metaHolderFactory = META_HOLDER_FACTORY_MAP.get(HystrixPointcutType.of(method));
        MetaHolder metaHolder = metaHolderFactory.create(joinPoint);
        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;
    }
    //......
}

支持@HystrixCommand及@HystrixCollapser注解

HystrixShutdownHook

	/**
	 * {@link DisposableBean} that makes sure that Hystrix internal state is cleared when
	 * {@link ApplicationContext} shuts down.
	 */
	private class HystrixShutdownHook implements DisposableBean {

		@Override
		public void destroy() throws Exception {
			// Just call Hystrix to reset thread pool etc.
			Hystrix.reset();
		}

	}

主要是调用了reset方法

hystrix-core-1.5.12-sources.jar!/com/netflix/hystrix/Hystrix.java

    /**
     * Reset state and release resources in use (such as thread-pools).
     * <p>
     * NOTE: This can result in race conditions if HystrixCommands are concurrently being executed.
     * </p>
     */
    public static void reset() {
        // shutdown thread-pools
        HystrixThreadPool.Factory.shutdown();
        _reset();
    }

    /**
     * Reset state and release resources in use (such as threadpools) and wait for completion.
     * <p>
     * NOTE: This can result in race conditions if HystrixCommands are concurrently being executed.
     * </p>
     * 
     * @param time
     *            time to wait for thread-pools to shutdown
     * @param unit
     *            {@link TimeUnit} for <pre>time</pre> to wait for thread-pools to shutdown
     */
    public static void reset(long time, TimeUnit unit) {
        // shutdown thread-pools
        HystrixThreadPool.Factory.shutdown(time, unit);
        _reset();
    }

    /**
     * Reset logic that doesn't have time/TimeUnit arguments.
     */
    private static void _reset() {
        // clear metrics
        HystrixCommandMetrics.reset();
        HystrixThreadPoolMetrics.reset();
        HystrixCollapserMetrics.reset();
        // clear collapsers
        HystrixCollapser.reset();
        // clear circuit breakers
        HystrixCircuitBreaker.Factory.reset();
        HystrixPlugins.reset();
        HystrixPropertiesFactory.reset();
        currentCommand.set(new ConcurrentStack<HystrixCommandKey>());
    }

小结

HystrixCircuitBreakerConfiguration主要是注入了HystrixCommandAspect以及HystrixShutdownHook。前者用于支持支持@HystrixCommand及@HystrixCollapser注解,后者用于shudown的时候进行一些清理工作。

doc

© 著作权归作者所有

共有 人打赏支持
go4it
粉丝 50
博文 670
码字总数 467155
作品 0
深圳
聊聊spring cloud gateway的GatewayFilter

序 本文主要研究一下spring cloud gateway的GatewayFilter GatewayFilter spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/GatewayFilter.jav......

go4it
06/09
0
0
聊聊spring.cloud.gateway.default-filters

序 本文主要研究下spring.cloud.gateway.default-filters 配置 default-filters,配置的是FilterDefinition对象 FilterDefinition spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/sp......

go4it
06/01
0
0
聊聊spring cloud netflix的HystrixCommands

序 本文主要研究一下spring cloud netflix的HystrixCommands。 maven 这个组件对hystrix进行了封装了,2.0.0.RELEASE全面支持了Reactor的Reactive Streams。 spring-cloud-starter-netflix-h...

go4it
06/22
0
0
聊聊eureka client的shutdown

序 本文主要研究一下eureka client的shutdown EurekaRegistration spring-cloud-netflix-eureka-client-2.0.0.RC1-sources.jar!/org/springframework/cloud/netflix/eureka/EurekaClientAuto......

go4it
05/04
0
0
聊聊WebClient的LoadBalance支持

序 本文主要研究一下WebClient的LoadBalance支持 代码实例 配置 请求department-service controller /flux/departments?orgId=1 异常情况 Connection refused instance can not be null 源码......

go4it
04/29
0
0
聊聊springcloud的serviceRegistryEndpoint

序 本文主要研究一下springcloud的serviceRegistryEndpoint 实例 GET /actuator/service-registry 如果eureka挂了,则返回 后台日志 POST /actuator/service-registry 在查看则返回 再去eur...

go4it
04/28
0
0
聊聊spring cloud的RequestHeaderToRequestUri

序 本文主要研究一下spring cloud的RequestHeaderToRequestUriGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gate......

go4it
06/16
0
0
聊聊spring cloud gateway的RedirectToGatewayFilter

序 本文主要研究下spring cloud gateway的RedirectToGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/confi......

go4it
06/13
0
0
聊聊spring cloud的LoadBalancerAutoConfiguration

序 本文主要研究一下spring cloud的LoadBalancerAutoConfiguration RibbonAutoConfiguration spring-cloud-netflix-ribbon-2.0.0.RC2-sources.jar!/org/springframework/cloud/netflix/ribb......

go4it
昨天
0
0
聊聊spring cloud gateway的SetStatusGatewayFilter

序 本文主要研究下spring cloud gateway的SetStatusGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/config......

go4it
06/15
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

ClassNotFoundException: javax.el.ELManager

这个是因为tomcat7中的el-api2.2,有些版本太低,建议升级tomcat到8.0,利用el-api3.0就会解决这个问题。

无语年华
7分钟前
0
0
Jvm堆内存的划分结构和优化,垃圾回收详解(详细解答篇)

在JVM中堆空间划分如下图所示 上图中,刻画了Java程序运行时的堆空间,可以简述成如下2条 1.JVM中堆空间可以分成三个大区,新生代、老年代、永久代 2.新生代可以划分为三个区,Eden区,两个幸...

嘻哈开发者
19分钟前
0
0
CentOS 7.4 设置系统字符编码

1.语言变量LANG在 /etc/locale 文件中。 2.可以通过/ect/profile 来修改LC_TYPE 变量的值 添加如下代码 export LC_ALL="zh_CN.GBK" export LANG="zh_CN.GBK" 到profile文件中,变量的可以修改...

qimh
20分钟前
0
0
Kafka相关使用

安装前提,需要有jdk环境,还有zookeeper环境 zookeeper下载地址:https://www.apache.org/dyn/closer.cgi/zookeeper/ zookeeper安装参考:https://www.jianshu.com/p/f7037105db46 kafka的下......

朝如青丝暮成雪
21分钟前
0
0
CentOS7 解决无法使用tab自动补全 tab代码提示

一、前言 对于刚刚开始学习linux的新人来说,linux的一切都显着神秘,只能惊叹于大牛在Linux上行云流水的操作。今天介绍一下在linux中自动补全的功能。 对于新人来说,在不懂得技巧的情况下,...

ziluopao
27分钟前
0
0
redis安装

https://www.cnblogs.com/feijl/p/6879929.html

ghou-靠墙哭
27分钟前
0
0
Spring核心——注解自动装载

从配置上扩展 之前的文章介绍了Spring的IoC容器配置管理方面的详细内容,需要了解的可以从IoC容器的设计模式开始阅读。在介绍基于注解配置的配置之前我们再重复一下在之前提到的基本认识: ...

随风溜达的向日葵
30分钟前
2
0
ElasticSearch学习(8)—— SearchType

Elasticsearch有四种类型的SearchType 1、query and fetch 向索引的所有分片(shard)都发出查询请求,各分片返回的时候把元素文档(document)和计算后的排名信息一起返回。这种搜索方式是最...

叶枫啦啦
32分钟前
0
0
MYSQL备份工具-mysqldump

介绍 mysqldump 是文本备份还是二进制备份 它是文本备份,如果你打开备份文件你将看到所有的语句,可以用于重新创建表和对象。它也有 insert 语句来使用数据构成表。 语法 mysqldump 的语法是...

郭恩洲_OSC博客
34分钟前
0
0
我的第一个go web框架

使用了beego等go web开发框架之后,感觉各种不方便,尤其是在接收参数、和自定义输出的时候,各种难受,定义各种model,这不是找事情嘛??尤其是在角色权限控制的时候我也感觉力不从心。。。...

独坐苔痕但观罗敷
34分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部