天天看点

SpringCloud 之 Hystrix断路器 及 Hystrix仪表盘

文章目录

        • 一、前情提要
            • 1.注册中心
            • 2、服务注册
        • 二、搭建Hystrix断路器
            • 1、引入依赖
            • 2、启动类上添加注解
            • 3、在调用服务的方法上添加@HystrixCommand注解,并通过fallbackMethod指定方法
            • 4、查看结果
        • 三、Hystrix仪表盘查看
            • 2、启动类上添加注解
            • 3、访问Hystrix仪表盘

一、前情提要

1.注册中心

server:
  port: 8000
  
  #注册中心地址
      defaultZone: http://127.0.0.1:8000/eureka
  
           

2、服务注册

server:
  port: 8100

spring:
  application:
    name: Hello-World
           

注册服务项目中的方法(被consumer调用)

/**
 * Created by yan on 2019/3/12.
 */
@Controller
public class TestController {

    @RequestMapping("test")
    @ResponseBody
    public String test(){

        return "那就这样吧";
    }
}
           

二、搭建Hystrix断路器

在我的consumer项目基础上搭建,半路进来的同志们进去扫一眼吧

1、引入依赖

<!--hystrix断路器-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
           

2、启动类上添加注解

//开启断路器功能
@EnableCircuitBreaker
           

3、在调用服务的方法上添加@HystrixCommand注解,并通过fallbackMethod指定方法

利用Thread的sleep模拟延迟阻塞3000ms,hystrix默认超时时间为2000ms,超过这个时间,服务就会认为是阻塞。超过时间则跳到指定方法

/**
 * Created by yan on 2019/3/12.
 */
@Controller
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("test")
    @ResponseBody
    @HystrixCommand(fallbackMethod="helloFallback")
    public String test(){
    	//让线程睡3s
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String body = restTemplate.getForEntity("http://HELLO-WORLD/test", String.class).getBody();
        return body;
    }

    public String helloFallback(){

        return "Error,I'm wrong!";
    }

}
           

4、查看结果

SpringCloud 之 Hystrix断路器 及 Hystrix仪表盘

超过了默认的2000ms便跳到了制定方法

三、Hystrix仪表盘查看

1、导入依赖

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

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

           

2、启动类上添加注解

//开启Hystrix仪表盘
@EnableHystrixDashboard
           

3、访问Hystrix仪表盘

SpringCloud 之 Hystrix断路器 及 Hystrix仪表盘

这里可以看到默认延迟(Delay)为2000ms

SpringCloud 之 Hystrix断路器 及 Hystrix仪表盘

继续阅读