Spring Cloud Hystrix(熔断器)介绍及使用

  • 内容
  • 评论
  • 相关

Hystrix 是 Netflix 针对微服务分布式系统采用的熔断保护中间件,相当于电路中的保险丝。

在分布式环境中,许多服务依赖项中的一些必然会失败。Hystrix 是一个库,通过添加延迟容忍和容错逻辑,帮助你控制这些分布式服务之间的交互。Hystrix 通过隔离服务之间的访问点、停止级联失败和提供回退选项来实现这一点,所有这些都可以提高系统的整体弹性。

在微服务架构下,很多服务都相互依赖,如果不能对依赖的服务进行隔离,那么服务本身也有可能发生故障,Hystrix 通过 HystrixCommand 对调用进行隔离,这样可以阻止故障的连锁效应,能够让接口调用快速失败并迅速恢复正常,或者回退并优雅降级。

Hystrix 的简单使用

创建一个空的 Maven 项目,在项目中增加 Hystrix 的依赖,代码如下所示。

<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-core</artifactId>
    <version>1.5.18</version>
</dependency>

编写第一个 HystrixCommand,代码如下所示。

public class MyHystrixCommand extends HystrixCommand<String> {
    private final String name;
    public MyHystrixCommand(String name) {
        super(HystrixCommandGroupKey.Factory.asKey("MyGroup"));
        this.name = name;
    }

    @Override
    protected String run() {
        return this.name + ":" + Thread.currentThread().getName();
    }
}

首先需要继承 HystrixCommand,通过构造函数设置一个 Groupkey。具体的逻辑在 run 方法中,我们返回了一个当前线程名称的值。写一个 main 方法来调用上面编写的 MyHystrixCommand 程序,代码如下所示。

public static void main(String[] args) throws InterruptedException, ExecutionException {
    String result = new MyHystrixCommand("zhangsan").execute();
    System.out.println(result);
}

输出结果如图 1 所示:

运行结果
图 1  运行结果

本文标题:Spring Cloud Hystrix(熔断器)介绍及使用

本文地址:http://www.hosteonscn.com/6640.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注