文档章节

聊聊spring cloud的HystrixCircuitBreakerConfiguration

go4it
 go4it
发布于 06/24 00:53
字数 756
阅读 25
收藏 2

本文主要研究一下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
粉丝 70
博文 793
码字总数 633078
作品 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
聊聊springcloud的serviceRegistryEndpoint

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

go4it
04/28
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

没有更多内容

加载失败,请刷新页面

加载更多

Spring应用学习——AOP

1. AOP 1. AOP:即面向切面编程,采用横向抽取机制,取代了传统的继承体系的重复代码问题,如下图所示,性能监控、日志记录等代码围绕业务逻辑代码,而这部分代码是一个高度重复的代码,也就...

江左煤郎
今天
2
0
eclipse的版本

Eclipse各版本代号一览表 Eclipse的设计思想是:一切皆插件。Eclipse核心很小,其它所有功能都以插件的形式附加于Eclipse核心之上。 Eclipse基本内核包括:图形API(SWT/Jface),Java开发环...

mdoo
今天
1
0
SpringBoot源码:启动过程分析(一)

本文主要分析 SpringBoot 的启动过程。 SpringBoot的版本为:2.1.0 release,最新版本。 一.时序图 还是老套路,先把分析过程的时序图摆出来:时序图-SpringBoot2.10启动分析 二.源码分析 首...

Jacktanger
今天
3
0
小白带你认识netty(二)之netty服务端启动(上)

上一章 中的标准netty启动代码中,ServerBootstrap到底是如何启动的呢?这一章我们来瞅下。 server.group(bossGroup, workGroup);server.channel(NioServerSocketChannel.class).optio...

天空小小
今天
3
0
聊聊storm trident batch的分流与聚合

序 本文主要研究一下storm trident batch的分流与聚合 实例 TridentTopology topology = new TridentTopology(); topology.newStream("spout1", spout) .p......

go4it
昨天
5
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部