聊聊spring cloud的HystrixAutoConfiguration

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

HystrixAutoConfiguration

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

/**
 * Auto configuration for Hystrix.
 *
 * @author Christian Dupuis
 * @author Dave Syer
 */
@Configuration
@ConditionalOnClass({ Hystrix.class, HealthIndicator.class })
@AutoConfigureAfter({ HealthIndicatorAutoConfiguration.class })
public class HystrixAutoConfiguration {

    @Bean
    @ConditionalOnEnabledHealthIndicator("hystrix")
    public HystrixHealthIndicator hystrixHealthIndicator() {
        return new HystrixHealthIndicator();
    }

    @Bean
    @ConditionalOnProperty(value = "management.metrics.hystrix.enabled", matchIfMissing = true)
    public HystrixMetricsBinder hystrixMetricsBinder() {
        return new HystrixMetricsBinder();
    }

    /**
     * See original {@link org.springframework.boot.actuate.autoconfigure.jolokia.JolokiaEndpointAutoConfiguration}
     */
    @Configuration
    @ConditionalOnWebApplication(type = SERVLET)
    @ConditionalOnBean(HystrixCommandAspect.class) // only install the stream if enabled
    @ConditionalOnClass({ HystrixMetricsStreamServlet.class })
    @EnableConfigurationProperties(HystrixProperties.class)
    protected static class HystrixServletAutoConfiguration {

        @Bean
        @ConditionalOnEnabledEndpoint
        public HystrixStreamEndpoint hystrixStreamEndpoint(HystrixProperties properties) {
            return new HystrixStreamEndpoint(properties.getConfig());
        }

        @Bean
        public HasFeatures hystrixStreamFeature() {
            return HasFeatures.namedFeature("Hystrix Stream Servlet", HystrixMetricsStreamServlet.class);
        }
    }

    @Configuration
    @ConditionalOnWebApplication(type = REACTIVE)
    @ConditionalOnBean(HystrixCommandAspect.class) // only install the stream if enabled
    @ConditionalOnClass({ DispatcherHandler.class })
    @EnableConfigurationProperties(HystrixProperties.class)
    protected static class HystrixWebfluxManagementContextConfiguration {

        @Bean
        @ConditionalOnEnabledEndpoint
        public HystrixWebfluxEndpoint hystrixWebfluxController() {
            Observable<String> serializedDashboardData = HystrixDashboardStream.getInstance().observe()
                    .concatMap(dashboardData -> Observable.from(SerialHystrixDashboardData.toMultipleJsonStrings(dashboardData)));
            Publisher<String> publisher = RxReactiveStreams.toPublisher(serializedDashboardData);
            return new HystrixWebfluxEndpoint(publisher);
        }

        @Bean
        public HasFeatures hystrixStreamFeature() {
            return HasFeatures.namedFeature("Hystrix Stream Webflux", HystrixWebfluxEndpoint.class);
        }
    }
}

这里有几个bean,一个是HystrixHealthIndicator,还有HystrixMetricsBinder。另外关于endpoint,区分了servlet及webflux版本。

HystrixHealthIndicator

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

/**
 * A {@link HealthIndicator} implementation for Hystrix circuit breakers.
 * <p>
 * This default implementation will not change the system state (e.g.  <code>OK</code>) but
 * includes all open circuits by name.
 *
 * @author Christian Dupuis
 */
public class HystrixHealthIndicator extends AbstractHealthIndicator {

    private static final Status CIRCUIT_OPEN = new Status("CIRCUIT_OPEN");

    @Override
    protected void doHealthCheck(Builder builder) throws Exception {
        List<String> openCircuitBreakers = new ArrayList<>();

        // Collect all open circuit breakers from Hystrix
        for (HystrixCommandMetrics metrics : HystrixCommandMetrics.getInstances()) {
            HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory
                    .getInstance(metrics.getCommandKey());
            if (circuitBreaker != null && circuitBreaker.isOpen()) {
                openCircuitBreakers.add(metrics.getCommandGroup().name() + "::"
                        + metrics.getCommandKey().name());
            }
        }

        // If there is at least one open circuit report OUT_OF_SERVICE adding the command
        // group
        // and key name
        if (!openCircuitBreakers.isEmpty()) {
            builder.status(CIRCUIT_OPEN).withDetail("openCircuitBreakers",
                    openCircuitBreakers);
        }
        else {
            builder.up();
        }
    }

}

检查断路器的状态

HystrixMetricsBinder

micrometer-core-1.0.5-sources.jar!/io/micrometer/core/instrument/binder/hystrix/HystrixMetricsBinder.java

@NonNullApi
@NonNullFields
public class HystrixMetricsBinder implements MeterBinder {

    @Override
    public void bindTo(MeterRegistry registry) {
        // Keeps references of existing Hystrix plugins.
        HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
        HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy();
        HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance().getCommandExecutionHook();
        HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy();

        HystrixPlugins.reset();

        // Registers existing plugins except the new MicroMeter Strategy plugin.
        HystrixPlugins.getInstance().registerMetricsPublisher(new MicrometerMetricsPublisher(registry));
        HystrixPlugins.getInstance().registerConcurrencyStrategy(concurrencyStrategy);
        HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
        HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
        HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
    }
}

这里导出metrics到micrometer

HystrixStreamEndpoint

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

/**
 * {@link org.springframework.boot.actuate.endpoint.annotation.Endpoint} to expose a Jolokia {@link HystrixMetricsStreamServlet}.
 *
 * @author Phillip Webb
 * @since 2.0.0
 */
@ServletEndpoint(id = "hystrix.stream")
public class HystrixStreamEndpoint implements Supplier<EndpointServlet> {

    private final Map<String, String> initParameters;

    public HystrixStreamEndpoint(Map<String, String> initParameters) {
        this.initParameters = initParameters;
    }

    @Override
    public EndpointServlet get() {
        return new EndpointServlet(HystrixMetricsStreamServlet.class)
                .withInitParameters(this.initParameters);
    }
}

这个是基于servlet的

HystrixWebfluxEndpoint

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

@RestControllerEndpoint(id = "hystrix.stream")
public class HystrixWebfluxEndpoint {

    private final Flux<String> stream;

    public HystrixWebfluxEndpoint(Publisher<String> dashboardData) {
        stream = Flux.interval(Duration.ofMillis(500)).map(aLong -> "{\"type\":\"ping\"}")
                .mergeWith(dashboardData).share();
    }

    // path needs to be empty, so it registers correct as /actuator/hystrix.stream
    @GetMapping(path = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> hystrixStream() {
        return stream;
    }
}

这个是基于webflux的

小结

HystrixAutoConfiguration主要是配置了HystrixHealthIndicator、HystrixMetricsBinder以及HystrixEndpoint(分servlet与webflux版本)。

doc

  • 14. Circuit Breaker: Hystrix Dashboard

原文发布于微信公众号 - 码匠的流水账(geek_luandun)

原文发表时间:2018-06-23

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏我的博客

Zend Framework自动加载、简单路由配置(Bootstrap.php)

<?php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { /* * 自动加...

37080
来自专栏Pulsar-V

OpenCV编译参数一览

全部参数一览 //Path to a program. ANT_EXECUTABLE:FILEPATH=D:/apache-ant-1.10.1/bin/ant...

92260
来自专栏技术小黑屋

Scan Media Files in Android

I once tried to use MediaScanner to resolve problems; however it turned out to b...

31020
来自专栏码匠的流水账

聊聊springcloud的GatewayControllerEndpoint

本文主要研究一下springcloud的GatewayControllerEndpoint

48910
来自专栏数据结构与算法

BZOJ1053: [HAOI2007]反素数ant(爆搜)

  对于任何正整数x,其约数的个数记作g(x)。例如g(1)=1、g(6)=4。如果某个正整数x满足:g(x)>g(i) 0<i<x

10720
来自专栏别先生

Caused by: java.net.ConnectException: Connection refused: master/192.168.3.129:7077

1:启动Spark Shell,spark-shell是Spark自带的交互式Shell程序,方便用户进行交互式编程,用户可以在该命令行下用scala编写spa...

1K60
来自专栏鸿的学习笔记

16位顶级数据科学家语录

Chief Data Scientist at The New York Times & Associate Professor of Applied Ma...

9820
来自专栏ml

HDUOJ---(4708)Herding

Herding Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (J...

361100
来自专栏hbbliyong

WPF Trigger for IsSelected in a DataTemplate for ListBox items

<DataTemplate DataType="{x:Type vm:HeaderSlugViewModel}"> <vw:HeaderSlug...

49640
来自专栏FD的专栏

Effective Testing with RSpec 3 (英文版)(序言)

Early praise for Effective Testing with RSpec 3

22440

扫码关注云+社区

领取腾讯云代金券