SpringCloud实战九:Spring Cloud Hystrix Dashboard
Hystrix Dashboard断路器监控,是作为断路器状态的一个组件,提供了数据监控和友好的图形化界面。通过配置Hystrix Dashboard,我们可以通过浏览页面看运行情况
上一张介绍了Hystrix,Hystrix Dashboard断路器监控,本章直接上代码,看看监控页面,基于上一篇的代码,在pom.xml中引入:
- 1.引入actuator与dashboard依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 2.在application.properties中添加配置,现在的actuator需要手动配置,暴露端点
# 暴露监控端点
management.endpoints.web.exposure.include=*
- 3.在启动主类上添加 @EnableHystrixDashboard 与 @EnableHystrix 注解
@RestController
@EnableHystrixDashboard
@EnableHystrix
@SpringBootApplication
public class HystrixDemoApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixDemoApplication.class, args);
}
// hystrix默认1秒超时,下面的随机方法可能让线程睡3秒,从而引发hystrix熔断降级,
// 观察dashboard界面,有百分比与圆点为红色则说明有熔断
@HystrixCommand(fallbackMethod = "getNameFallback" ,
threadPoolKey = "hystrixDemoThreadPool",
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"),
@HystrixProperty(name = "maxQueueSize", value = "10")
})
@RequestMapping("/test")
public String test(String username){
randomlyRunLong();
return "randomlyRunLong"+username;
}
// 1/3的机率会让线程睡3秒
private void randomlyRunLong() {
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
if (randomNum == 3) sleep();
}
//线程睡3秒
private void sleep() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 出错后会调用该降级方法,返回指定的信息
*
* @param username
* @return
*/
public String getNameFallback(String username) {
return " this username is not exist ";
}
}
- 4.启动项目,访问 http://localhost:8080/hystrix ,注意红色框框中的hystrix.stream流地址需要加actuator:
在上面的文本框中输入:http://localhost:8080/actuator/hystrix.stream ,再点击下面的 Monitor Stream按钮,进入dashboard监控页面 - 5.访问 http://localhost:8080/test ,多刷新几次,再观察 dashboard 监控页面
对监控图的一些数据进行简要解释: - test:为请求的名称,HystrixCommand注解上的方法
- 12为成功请求数
- 6为超时请求数
- 33%为10秒内错误百分比
- Host为单机请求率
- Cluster为集群请求率
- Cirecuit为断路器状态,Closed为闭合,表示没有进行熔断
- Pool Size为20,设置线程池是30,因为请求量小,没有达到最大值
- Queue Size为5,设置的10,因为请求量小,没有达到最大值
好了,完成了Hystrix Dashboard 单机监控页面,在微服务环境中,Dashboard往往依赖 Turbine,它是一个聚合服务,因为我们的应用程序一般是以集群的方式部署的,有很多应用实例,我们可以把hystrix单个的流放到dashboard中查看,但是更需要看集群流量的情况,请求的错误数和成功数需要聚合在一起相加后对外显示的,那么这个时候流需要做聚合
代码已上传至码云,源码,项目使用的版本信息如下:
- SpringBoot 2.0.6.RELEASE
- SpringCloud Finchley.SR2