Hystrix 的简单使用

Hystrix 入门


在分布式环境中总会有一些服务会失效,Hystrix是Netfix下的一个java库,通过添加阀值及容错逻辑来帮我们控制分布式系统间的交互,通过隔离服务间的访问点、停止级联故障、提供可退回操作来实现容错故障,比如下图所示,两个服务之间调用,如果服务B服务挂了或者响应超时了,Hystrix就会及时通过隔离服务间的访问点,并通过之前设置好的fallback内容通知用户。

Hystrix 的简单使用

本节代码地址

GitHub: fw-spring-cloud


1.Hystrix 的简单实用

下面我们通过新建项目一步一步进入Hystrix 的篇章。

1.1 新建项目

此项目是不在Spring Cloud下运行的,仅仅演示Hystrix的特性,后续会专门讲解和Spring Cloud的使用。

Hystrix 的简单使用

1.2 添加Maven配置

<code><dependencies>
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-web/<artifactid>
/<dependency>
<dependency>
<groupid>com.netflix.hystrix/<groupid>
<artifactid>hystrix-core/<artifactid>
<version>${hystrix-core.version}/<version>
/<dependency>
<dependency>
<groupid>commons-configuration/<groupid>
<artifactid>commons-configuration/<artifactid>
<version>${commons-configuration.version}/<version>
/<dependency>
/<dependencies>
/<code>

1.3 新建HystrixCommand 类

下面我们编写一个HystrixCommand的实现类,通过设置一个Groupkey。具体的逻辑卸载run()方法中,并在方法中输出当前的线程名,本节我们都将通过main()方法调用。

命令组名称(Groupkey) 是必传的,默认情况下全局维护的线程池Map以该值作为Key,该Map的Value为执行命令的线程池。

<code>/**
* @author xuyisu
* @description 简单使用
* @date 2019/12/30
*/
public class FwHystrixCommond extends HystrixCommand<string> {
private final String name;
protected FwHystrixCommond(String name) {
//创建一个组名
super(HystrixCommandGroupKey.Factory.asKey("myGroup"));
this.name=name;

}

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

// 非异步执行
// public static void main(String[] args) {
// String test = new FwHystrixCommond("test").execute();
// System.out.println(test);
// }
// 异步执行
public static void main(String[] args) throws ExecutionException, InterruptedException {
Future<string> test = new FwHystrixCommond("test").queue();
System.out.println(test.get());
}
}
/<string>/<string>/<code>

右键运行之后,可以看到正常的输出,并且我们的组名变成了线程的名字

<code>test:hystrix-myGroup-1/<code>


更多更全的微服务相关的内容请 Git 搜索 fw-spring-cloud


分享到:


相關文章: