• Spring Cloud Hystrix 断路器


    1.继承feign和ribbon

    2.ribbon服务修改内容

    新增依赖pom.xml:

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>

    3.在启动类增加注解:@EnableHystrix

    4.修改service类,增加断路返回:

        @Service
        public class HelloService {
            @Autowired
            RestTemplate restTemplate;
    
            @HystrixCommand(fallbackMethod = "hiError")
            public String hiService(String name) {
                return restTemplate.getForObject("http://eurekaclient/hi?name="+name,String.class);
            }
    
            public String hiError(String name) {
                return "hi,"+name+",sorry,error!";
            }
        }

    5.测试,当对应的服务关闭时,访问对应服务返回如下:

    6.feign原本就继承了断路功能,需要在配置里打开:

    application.yml新增下面内容:

    feign:
      hystrix:
          enabled: true

    7.在客户端服务接口上增加注解时,加上fallback参数即可

    @FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class)

    8.然后写这个接口的一个实现类SchedualServiceHiHystric

    package com.bennytitan.servicefeign;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class SchedualServiceHiHystric implements SchedualServiceHi {
        @Override
        public String sayHiFromClientOne(String name) {
            return "sorry "+name;
        }
    }

    这样就完成了。

    9.如果要加入Hystrix Dashboard来打开断路器仪表盘页面显示断路器工作情况。需要增加依赖:

            <!-- 断路器仪表盘 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
            </dependency>

    10.在配置bean增加下面的bean配置:

        @Bean
        ServletRegistrationBean getServlet(){
            HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
            ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
            registrationBean.setLoadOnStartup(1);
            registrationBean.addUrlMappings("/hystrix.stream");
            registrationBean.setName("HystrixMetricsStreamServlet");
            return registrationBean;
        }

    11.在服务启动类里添加注解:@EnableHystrixDashboard

    12.测试访问:http://localhost:8764/hystrix

    打开页面,输入红框内的内容后点击按钮

    完成。

  • 相关阅读:
    享受法国葡萄酒
    shell (bash) hot keys
    传统MapReduce框架
    【oracle】常用命令
    【转】商业J2EE中间件价值何在?
    【转】Linux(CentOS)服务器上安装Webmin
    【转】CentOS 5安装免费主机控制面板Webmin
    【源码】不规则矩形窗体的设计
    【转】虚拟机VirtualBox+Centos+NAT网络的配置过程
    【jsp】 config配置的关键字
  • 原文地址:https://www.cnblogs.com/BennyTitan/p/9198418.html
Copyright © 2020-2023  润新知