Hystrix监控
除了隔离依赖服务的调用以外,Hystrix还提供了近实时的监控,Hystrix会实时、累加地记录所有关于HystrixCommand的执行信息,包括每秒执行多少请求多少成功,多少失败等。Netflix通过hystrix-metrics-event-stream项目实现了对以上指标的监控。
我们先启动一个包含具有Hystrix服务
新建项目,在项目中添加依赖
<!-- 整合hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
随便添加一个接口
@RestController
public class RibbonHystrixController {
@Autowired
private RibbonHystrixService ribbonHystrixService;
@GetMapping("/ribbon/{id}")
public User findById(@PathVariable Long id) {
return this.ribbonHystrixService.findById(id);
}
@Service
public class RibbonHystrixService {
@Autowired
private RestTemplate restTemplate;
private static final Logger LOGGER = LoggerFactory.getLogger(RibbonHystrixService.class);
/**
* 使用@HystrixCommand注解指定当该方法发生异常时调用的方法
* @param id id
* @return 通过id查询到的用户
*/
@HystrixCommand(fallbackMethod = "fallback")
public User findById(Long id) {
return this.restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
}
/**
* hystrix fallback方法
* @param id id
* @return 默认的用户
*/
public User fallback(Long id) {
RibbonHystrixService.LOGGER.info("异常发生,进入fallback方法,接收的参数:id = {}", id);
User user = new User();
user.setId(-1L);
user.setUsername("default username");
user.setAge(0);
return user;
}
}
启动该项目后,输入http://localhost:8011/hystrix.stream
二、新建多一个项目添加如下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
启动,后浏览器输入http://localhost:8030/hystrix.stream可以看到,并且将上一个服务的监控地址写入
请求http://localhost:8011/ribbon/1我们可以看到控制台的相关监控信息