码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Cloud Hystrix 断路器

时间:2018-06-19 16:14:50      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:setname   localhost   import   继承   group   页面   ppi   host   ice   

 

 

 

 

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

打开页面,输入红框内的内容后点击按钮技术分享图片

 

技术分享图片

完成。

Spring Cloud Hystrix 断路器

标签:setname   localhost   import   继承   group   页面   ppi   host   ice   

原文地址:https://www.cnblogs.com/BennyTitan/p/9198418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!