Hystrix是Netflix开源的一款针对分布式系统的延迟和容错库,目的是用来隔离分布式服务故障。它提供线程和信号量隔离,以减少不同服务之间资源竞争带来的相互影响;提供优雅降级机制;提供熔断机制使得服务可以快速失败,而不是一直阻塞等待服务响应,并能从中快速恢复。Hystrix通过这些机制来阻止级联失败并保证系统弹性、可用。
1.ribbon整合hystrix
首先,在消费者导入hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在springboot启动类上加上注解@EnableHystrix
在consumer本地准备降级方法"myFallback",并为可能需要降级的相关方法加上@HystrixCommand注解,并指定降级方法"myFallback"
@RestController
public class ConsumerController {
@Autowired
public RestTemplate restTemplate;
@RequestMapping("/helloConsumer")
@HystrixCommand(fallbackMethod = "myFallback")
public String hello() {
System.out.println("consumer被调用...");
String result = restTemplate.getForObject("http://provider/helloProvider", String.class);
return result;
}
public String myFallback() {
System.out.println("myFallback被调用...");
return "服务繁忙,请稍后再试...";
}
}
分别启动注册中心10000,两个provider8080和8081(集群),以及一个consumer9090
重复访问http://localhost:9090/helloConsumer,两个provider正常轮询
关掉8080,继续重复访问,发现当轮询到8080时,myFallback被调用,因为此时8080服务器由于挂掉了而无法响应,因此发生服务降级
继续重复访问,发现请求都发送到了8081,因为此时hystrix已经对8080服务器进行了熔断,此时断路器为开启状态.但是一段时间(默认5秒)后,断路器会进入半开状态,它会判断下一次的请求结果,如果成功,断路器会进入关闭状态,否则会再次开启.
我们再次启动8080,访问http://localhost:9090/helloConsumer,发现轮询又回来了.这说明断路器又回到了关闭状态
2.feign整合hystrix
springcloud默认已经为feign整合了hystrix,但是它默认是关闭的,因此我们需要去application.yml配置文件中启用它
#端口
server:
port: 9091
#服务名称
spring:
application:
name: feign-consumer
eureka:
client:
service-url:
defaultZone: http://www.aaa.com:10000/eureka,http://www.bbb.com:10001/eureka,http://www.ccc.com:10002/eureka
feign:
hystrix:
enabled: true #开启hystrix
重复上面实验,hystrix正常工作.
3.hystrix监控仪表盘DashBoard的使用
新建springboot子工程hystrix_dashboard
导入依赖
<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>
在springboot启动类加上注解@EnableHystrixDashboard
在application.yml中配置端口号10086
server:
port: 10086
启动,访问http://localhost:10086/hystrix
没完,现在想要监测其它服务hystrix的情况,还要做些事.
比如我想将消费者9091作为监测的对象,那么首先得给它配一个hystrix.stream的servlet,如下:
@Configuration
public class WebConfig {
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet hystrixMetricsStreamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean<HystrixMetricsStreamServlet> servletRegistrationBean = new ServletRegistrationBean();
servletRegistrationBean.setServlet(hystrixMetricsStreamServlet);
servletRegistrationBean.addUrlMappings("/hystrix.stream");
return servletRegistrationBean;
}
}
然后,启动9091
在dashboard监测页面中的地址栏输入http://localhost:9091/hystrix.stream,点击Monitor Stream,同时调一下9091的接口,这样,我们就可以在dashboard页面进行实时监控了.