1. 回顾spring
上文讲解了使用Hystrix为Feign添加回退,并经过Fallback Factory检查回退缘由以及如何为Feign客户端禁用Hystrix。浏览器
2. Hystrix的监控架构
除实现容错外,Hystrix还提供了近乎实时的监控。HystrixCommand和HystrixObservableCommand在执行时,app
会生成执行结果和运行指标,好比每秒执行的请求数、成功数等,这些监控数据对分析应用系统的状态颇有用。ide
使用Hystrix的模块 hystrix-metrics-event-stream ,就可将这些监控的指标信息以 text/event-stream 的格式spring-boot
暴露给外部系统。spring-cloud-starter-hystrix包含该模块,在此基础上,只须为项目添加spring-boot-starter-actuator,微服务
就可以使用 /hystrix.stream 端点获取Hystrix的监控信息了。测试
> 启动项目 microservice-discovery-eurekaui
> 启动项目 microservice-provider-userspa
> 修改项目 microservice-consumer-movie-ribbon-hystrix 的启动类。添加以下方法
/** * 低版本直接启动便可使用 http://ip:port/hystrix.stream 查看监控信息 * 高版本须要添加本方法方可以使用 http://ip:port/hystix.stream 查看监控信息 * * @return */ @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; }
> 启动项目 microservice-consumer-movie-ribbon-hystrix
> 访问 http://localhost:8010/hystrix.stream,可看到浏览器一直处于请求的状态,页面一直处于请求状态,并一直打印ping。
由于此时项目中注解了 @HystrixCommand 的方法尚未执行,所以也没有任何的监控数据
> 访问 http://localhost:8010/user/1 后,再次访问 http://localhost:8010/hystrix.stream,可看到页面会从新出现相似于下面的内容。
由于系统会不断地刷新以得到实时的监控数据。Hystrix的监控指标很是全面,例如HystrixCommand的名称、group名称、
断路器状态、错误率、错误数等。
3. Feign项目的Hystrix监控
启动前文的microservice-consumer-movie-feign-hystrix-fallback项目,并使用相似的方式测试,而后访问 http://localhost:8010/hystrix.stream,
发现返回的是404。这是为何呢?查看项目的依赖树发现,项目中并无hystrix-metrics-event-stream的依赖。
解决方案以下:
> 1. 复制项目 microservice-consumer-movie-feign-hystrix-fallback,将ArtifactId修改成 microservice-consumer-movie-feign-hystrix-fallback-stream.
> 2. 为项目添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
> 3. 在启动类上添加 @EnableCircuitBreaker ,这样就使用/hystrix.stream端点监控Hystrix了。
4. 总结
本文讲了Hystrix的监控,可是访问/hystrix.stream端点得到的数据是以文字形式展现的。很难经过这些数据,一眼看出系统当前的运行状态。
下文将讲解可视化监控数据。敬请期待~~~
5. 参考
周立 --- 《Spring Cloud与Docker微服务架构与实战》