天气晴,有风
调研 Hystrix 是今天一半的工作内容,另一半是更新项目的 Wiki 页面。
写了一个 Hystrix demo 程序:两个 REST 服务,其中一个会调用另一个,被调用的那个 REST 服务会随机失败,模拟服务异常的情况。Demo 程序启用了 Hystrix 和 Hystrix Dashboard 这两个功能。
得益于 Spring Boot,整个程序基本上就一个类
主程序:
@SpringBootApplication
@RestController
@EnableCircuitBreaker
@EnableHystrixDashboard
public class HystrixApplication {
RestTemplate restTemplate = new RestTemplate();
@HystrixCommand
@RequestMapping(value = "/refunds", method = RequestMethod.POST)
public String refund(@RequestBody Order order) {
return restTemplate.postForObject("http://localhost:8080/payments", order, String.class);
}
@RequestMapping(value = "/payments", method = RequestMethod.POST)
public String pay(@RequestBody Order order) {
Random random = new Random();
int nextInt = random.nextInt(10);
if (nextInt < 1) {
return "Order " + order.getCode() + " refunds success";
} else {
throw new RuntimeException("failed");
}
}
public static void main(String[] args) {
SpringApplication.run(HystrixApplication.class, args);
}
}
curl 测试脚本:
#!/usr/bin/env bash
timestamp() {
date +"%s"
}
for i in {1..100}
do
# echo "{\"code\": $(timestamp)}"
curl --data "{\"code\": $(timestamp)}" --header "Content-Type:application/json" -X POST "http://localhost:8080/refunds"
#sleep 1
done
通过访问 localhost:8080/hystrix
,我们能看到 Hystrix Dashboard 页面。填入一个 Stream 地址:localhost:8080/hystrix.stream
,我们就能看到 Hystrix 所统计出来的服务调用情况。Dashboard 可以显示出每个 @HystrixCommand
注释所表示的服务一定时间内调用成功和失败的次数,以及其它一些信息。
这个“一定时间内”是我之前理解失误的地方。我之前走马观花地了解了一下 Hystrix,误以为其 Dashboard 统计的整个服务生命周期里面的统计数据。实际情况是,Hystrix 统计的是一定时间内的数据。这个“一定时间”指的是其失败阀值时间。即默认配置下,5秒内最多不超过20次失败,否则即熔断。这个一定时间就是指的“5秒钟”。
所以,这样的方式显然不能作为应用监控来使用。其实 Spring Boot 本身就自带了一个 Metrics 的功能。通过这个功能,我们可以得到很多应用相关的数据,其中包括了服务返回 200 0K、500 Error 等 HTTP 状态码的次数等等。
这个功能启发了我们。其实,通过 AOP 的方式,我们可以拦截并统计远程调用的客户端的服务调用情况。比如,我们可以拦截 Spring RestTemplate 的各个方法,已得知其调用各种服务的情况。包括一段时间之内的平均响应时间,已经相对应的参数。
当然,在做这些之前,我们应该调研,是否已经有了响应的工具可以实现我们的目的。包括我之前提到的 CAT。
最后的最后。。。。好像有点感冒,擦