1. 前言
当我们开发了很多微服务,编写了很多接口,使用过程中,我们需要有个工具来实时监控这个接口的使用情况,保存请求数量,发生错误数量等。这个时候我们就需要Hystrix-dashboard。
2. 什么是Hystrix-dashboard
Hystrix-dashboard是一款针对Hystrix进行实时监控的工具,通过Hystrix Dashboard我们可以在直观地看到各Hystrix Command的请求响应时间, 请求成功率等数据。
3. 代码编写
3.1 对my-student的修改
修改StuApplication.java文件
加入这段代码
@Beanpublic ServletRegistrationBean getSerlet(){ HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/actuator/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean;}
完整的启动文件如下:
package com.student;@SpringBootApplication@EnableEurekaClient@EnableScheduling //启动Scheduled定时任务机制@EnableFeignClients@EnableCircuitBreaker@MapperScan("com.student.dao")public class StuApplication { public static void main(String[] args) { SpringApplication.run(StuApplication.class); } @Bean public ServletRegistrationBean getSerlet(){ HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/actuator/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean; }}
3.2 新建my-hystrixDashboard微服务
3.2.1 引入依赖
除了
spring-boot-starter-webspring-cloud-starter-netflix-eureka-clientspring-cloud-starter-configspring-cloud-starter-netflix-hystrix
hystrixDashboard需要引入两个新的依赖
org.springframework.cloud spring-cloud-starter-netflix-hystrix-dashboard org.springframework.boot spring-boot-starter-actuator
3.2.2 编写配置文件my-histrixDashboard-dev.yml
#配置端口号server: port: 8806#注册到注册中心eureka: client: service-url: defaultZone: http://localhost:8801/eureka/# 开启熔断feign: hystrix: enable: true
3.2.3 编写HystrixDashboardApp.java
package com.hystrixdashboard;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;@SpringBootApplication@EnableDiscoveryClient@EnableHystrixDashboardpublic class HystrixDashboardApp { public static void main(String[] args) { SpringApplication.run(HystrixDashboardApp.class); }}
4. 验证
注意各个微服务的启动顺序
eureka-config-HystrixDashboard-zuul-各个微服务
在浏览器输入框中输入:http://localhost:8806/hystrix
其中,8806是HystrixDashboard端口号
在1处输入我们需要监控的微服务的ip和端口,比如我们需要监控my-student的微服务,输入:http://localhost:8805/actuator/hystrix.stream 。然后点击“Monitor Stream"按钮。
便会看到my-student的接口使用情况。(一般第一次进入这个页面会是空白的,但是一旦有数据访问接口,dashboard中就有数据监控了。
同样,如果我们想同时监控my-user这个微服务。我们再打开一个新的窗口,输入:http://localhost:8806/hystrix
然后输入:http://localhost:8802/actuator/hystrix.stream,点击按钮。就会进入my-user的监控页面。