SpringCloud入坑记-Hystrix组件

在这里插入图片描述

简介(是什么)

在这里插入图片描述

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所解决的问题有详细的介绍:

  1. 用户请求需要依赖服务A、P、H、I,所有服务正常时,用户能得到正确响应,系统稳定运行;
    在这里插入图片描述
  2. 在系统请求量超过50次/秒后,服务出现了一定延迟,请求可能会达到秒级;
    在这里插入图片描述
  3. 系统请求量持续走高,服务I从高延迟到彻底不可用,要是有其他服务依赖服务I,就可能导致这些服务也高延迟或不可用,久而久之,可能导致整个系统出现大量请求堆积,系统整体响应迟缓。

此时,急需一种手段来保证某些服务不可用时,整个系统还能正常访问,甚至正确处理用户请求。

Hystrix正是在这种背景下诞生,它主要提供了下面几种功能:

  • 包装请求:使用HystrixCommand命令模式包裹请求
  • 跳闸:当服务错误率超过阈值时,自动跳闸,暂停请求该服务
  • 资源隔离:每个服务都存在一个资源池,资源池用完,请求就快速失败
  • 监控:实时监控服务运行状态

(怎么用)

  1. 新建项目ms-f1-order-hystrix,内容复制于ms-e1-order-feign

  2. 添加依赖:

<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已经足够满足现在项目的各种需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cj96248

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值