简介(是什么)
Hystrix是Spring Cloud
中又一重要组件,主要用来处理分布式系统中的容错需求。
借用Hystrix的github介绍:
Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.
Hystrix是一个延迟与容错的库,旨在隔离远程系统、服务和第三方库,阻止级联故障,提供在复杂分布式系统中恢复的能力。
解决的问题(能干什么)
Hystrix官方对于Hystrix所解决的问题有详细的介绍:
- 用户请求需要依赖服务A、P、H、I,所有服务正常时,用户能得到正确响应,系统稳定运行;
- 在系统请求量超过50次/秒后,服务出现了一定延迟,请求可能会达到秒级;
- 系统请求量持续走高,服务I从高延迟到彻底不可用,要是有其他服务依赖服务I,就可能导致这些服务也高延迟或不可用,久而久之,可能导致整个系统出现大量请求堆积,系统整体响应迟缓。
此时,急需一种手段来保证某些服务不可用时,整个系统还能正常访问,甚至正确处理用户请求。
Hystrix正是在这种背景下诞生,它主要提供了下面几种功能:
- 包装请求:使用HystrixCommand命令模式包裹请求
- 跳闸:当服务错误率超过阈值时,自动跳闸,暂停请求该服务
- 资源隔离:每个服务都存在一个资源池,资源池用完,请求就快速失败
- 监控:实时监控服务运行状态
(怎么用)
-
新建项目
ms-f1-order-hystrix
,内容复制于ms-e1-order-feign
。 -
添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
3、添加注解@EnableCircuitBreaker
到项目启动类:
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class OrderHystrixApp
{
public static void main( String[] args )
{
SpringApplication.run(OrderHystrixApp.class, args);
}
}
4、添加容错回调函数:
首先在需要处理的方法上添加注解@HystrixCommand
@HystrixCommand(fallbackMethod = "listFallback")
public List<Product> findAll(){
return feignService.list();
}
注解中需要指定的回调函数:
/**
* 为了保证其他业务正常运行,这里返回内容为空的List
*/
public List<Product> listFallback(){
return new ArrayList<>();
}
5、测试:启动相关项目,在浏览器中访问
http://localhost:10060/order/list
返回正确结果,然后停掉product-service
,再次请求,发现响应没有报错,而是在一段时间后返回了之前定义的空值。
Dashboard
Hystrix Dashboard 仪表盘用来展示当前系统执行请求状态的,可以让监控数据图形化。
1、新建项目ms-f2-order-hystrix-dashboard
,内容复制于ms-f1-order-hystrix
。
2、添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
3、在启动类上添加注解@EnableHystrixDashboard
,效果如下:
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrixDashboard
public class OrderHystrixApp{
4、测试:启动相关项目,在浏览器中访问
http://localhost:10062/hystrix.stream
在浏览器中请求几次,发现Dashboard会动态变化。
组件现状
下面的解释来自Hystrix的github,该组件现在只维护,不更新,提交的bug也不再积极处理,如果想扩展其他功能,只能自己fork一份添加了。
Hystrix is no longer in active development, and is currently in maintenance mode.
Hystrix 项目目前已经不在活跃,而转为维护阶段。
Hystrix (at version 1.5.18) is stable enough to meet the needs of Netflix for our existing applications.
Hystrix已经足够满足现在项目的各种需求。