聊聊spring cloud的HystrixCircuitBreakerConfiguration
序
本文主要研究一下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 {@Beanpublic HystrixCommandAspect hystrixCommandAspect() {return new HystrixCommandAspect();}@Beanpublic HystrixShutdownHook hystrixShutdownHook() {return new HystrixShutdownHook();}@Beanpublic 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;@Autowiredprivate HystrixMetricsProperties metricsProperties;private ObjectMapper mapper = new ObjectMapper();private HystrixMetricsPoller poller;private Set<String> reserved = new HashSet<String>(Arrays.asList("group", "name","type", "currentTime"));@Overridepublic void start() {if (this.gauges == null) {return;}MetricsAsJsonPollerListener listener = new MetricsAsJsonPollerListener() {@Overridepublic 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 listenerthis.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);}}}}@Overridepublic void stop() {if (this.poller != null) {this.poller.shutdown();}}@Overridepublic boolean isRunning() {return this.poller != null ? this.poller.isRunning() : false;}@Overridepublic int getPhase() {return Ordered.LOWEST_PRECEDENCE;}@Overridepublic boolean isAutoStartup() {return true;}@Overridepublic 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 {@Overridepublic 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 {@Overridepublic 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-poolsHystrixThreadPool.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-poolsHystrixThreadPool.Factory.shutdown(time, unit);_reset();}/*** Reset logic that doesn't have time/TimeUnit arguments.*/private static void _reset() {// clear metricsHystrixCommandMetrics.reset();HystrixThreadPoolMetrics.reset();HystrixCollapserMetrics.reset();// clear collapsersHystrixCollapser.reset();// clear circuit breakersHystrixCircuitBreaker.Factory.reset();HystrixPlugins.reset();HystrixPropertiesFactory.reset();currentCommand.set(new ConcurrentStack<HystrixCommandKey>());}
复制代码
小结
HystrixCircuitBreakerConfiguration主要是注入了HystrixCommandAspect以及HystrixShutdownHook。前者用于支持支持@HystrixCommand及@HystrixCollapser注解,后者用于shudown的时候进行一些清理工作。
doc
- 13. Circuit Breaker: Hystrix Clients
聊聊spring cloud的HystrixCircuitBreakerConfiguration相关推荐
- 聊聊spring cloud gateway的GlobalFilter
序 本文主要研究一下spring cloud gateway的GlobalFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0 ...
- 从架构演进的角度聊聊Spring Cloud都做了些什么?
Spring Cloud作为一套微服务治理的框架,几乎考虑到了微服务治理的方方面面,之前也写过一些关于Spring Cloud文章,主要偏重各组件的使用,本次分享主要解答这两个问题:Spring Cl ...
- 聊聊Spring Cloud版本的那些事儿
继续昨天说的计划,解惑一下收到比较多的问题. 有朋友问"为什么在很多文章中,大家引用的Spring版本名字都不一样呢?比如:Angel.SR6,Brixton.SR5等等,它们都有什么区别呢 ...
- 聊聊spring cloud gateway的PreserveHostHeaderGatewayFilter
序 本文主要研究下spring cloud gateway的PreserveHostHeaderGatewayFilter GatewayAutoConfiguration spring-cloud- ...
- 聊聊spring cloud的LoadBalancerAutoConfiguration
序 本文主要研究一下spring cloud的LoadBalancerAutoConfiguration RibbonAutoConfiguration spring-cloud-netflix-ri ...
- 聊聊spring cloud的DefaultEurekaServerContext
序 本文主要研究一下spring cloud的DefaultEurekaServerContext EurekaServerAutoConfiguration @Configuration @Impo ...
- 聊聊 Spring Cloud Config
一般服务器的应用都有以下几种类型, 其中当属业务部分最多也最繁杂. 当应用越来越庞大和复杂时,单机就肯定不能满足需求了,然后就要考虑分布式了,接下可能会应用不同的语言来开发应用. 比如 nginx 毫 ...
- 聊聊spring cloud gateway的SecureHeadersGatewayFilter
序 本文主要研究下spring cloud gateway的SecureHeadersGatewayFilter GatewayAutoConfiguration @Configuration @Co ...
- 聊聊spring cloud gateway的XForwardedHeadersFilter
序 本文主要研究spring cloud gateway的XForwardedHeadersFilter GatewayAutoConfiguration spring-cloud-gateway-c ...
- 聊聊spring cloud gateway的SetStatusGatewayFilter
序 本文主要研究下spring cloud gateway的SetStatusGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-c ...
最新文章
- Eclipse 菜单
- Android WebView 和 javaScript的互相调用(三)
- 2017matlab版本Simulink 学习笔记整理
- 5G 和云原生时代的技术下半场,视频化是最大最新的确定性
- clousx6机器人怎么导入词库_全国二等奖,临安学子登上机器人大赛国家级舞台...
- JAVA入门级教学之(简单的程序测试)
- 2016 版 Laravel 系列入门教程(三)【最适合中国人的 Laravel 教程】
- [转载] Java异常处理习题
- adobe reader打开pdf闪退或自动关闭
- 如何使用Beckhoff平台进行串口通讯(EL6002,EL6022)
- x86汇编游戏——2048
- 【CSDN浏览器助手】这款插件忒好用了
- 神来之笔之傅里叶变换(Fourier Tranformation)
- 关于Bmob后端云的使用
- a java exception has occured java
- dataframe读取以文本形式储存的excel中的数字
- iOS App 唤醒另一个App
- celery异步——生产者消费者
- android studio最新教程pdf下载,android studio教程pdf下
- 如何在WORD中输入方框,并且在里面打勾?