一. 创建 Hystrix Dashboard 监控服务
- Hystrix 除了可以实现服务隔离降级,熔断,限流以外,还提供了对 Hystrix 熔断降级服务调用准实时的监控 Hystrix Dashboard,用于图形化界面,以统计报表和图形的形式展示,包括每秒执行了多少请求,多少成功,失败等数据, SpringCloud 整合了 Hystrix Dashboard依赖
- 是一个服务项目,需要引入依赖创建启动
- 与创建普通的 SpringCloud 微服务项目相同,创建 Hystrix Dashboard 监控项目,pom文件引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<!--图形化界面必须要有 spring-boot-starter-actuator 依赖,并且该依赖要与web依赖配合放到一块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 监控服务的 yml 文件中只需要配置端口号即可
server:
port: 9001
- 创建监控项目的启动类,启动类添加 @EnableHystrixDashboard 修饰 ,当前服务为监控服务开启监控
@SpringBootApplication
@EnableHystrixDashboard //开启 HystrixDashboard 服务监控
public class HystrixDashboard9001 {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboard9001.class,args);
}
}
二. 被监控服务
- 被监控的服务项目中要添加 spring-boot-starter-actuator 依赖,并且该依赖要在spring-boot-starter-web依赖的下方紧挨着
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 被监控的服务启动类,添加 @EnableHystrix 注解修饰,并且创建 ServletRegistrationBean 注入到容器中
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableFeignClients
@EnableHystrix //开启Hystrix
public class OrderFeignHystixMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignHystixMain80.class,args);
}
/**
* 此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑
* ServletRegistrationBean因为SpringBoot的默认路径不是 “/hystrix.stream"
* 只要在自己的项目里配置上下的servlet就可以了
*/
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet() ;
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
- 被监控服务 yml (不需要其它关于 Dashboard 的配置)
三. 启动项目查看 Hystrix Dashboard 图形化界面
-
启动监控项目访问"http://监控项目ip:端口号/hystrix" 进入 Hystrix Dashboard
-
输入需要被监控的服务进行查看 “http://被监控服务的ip:端口号/hystrix.stream” 进入监控页面,当请求被监控的服务中通过 Hystrix 设置熔断间接的方法时,该页面会发生变化