1Hystrix 简单使用 · SpringCloud微服务实战 · 看云
导航
在分布式环境中总会有一些服务会失效,Hystrix是Netfix下的一个java库,通过添加阀值及容错逻辑来帮我们控制分布式系统间的交互,通过隔离服务间的访问点、停止级联故障、提供可退回操作来实现容错故障,比如下图所示,两个服务之间调用,如果服务B服务挂了或者响应超时了,Hystrix就会及时通过隔离服务间的访问点,并通过之前设置好的fallback内容通知用户。
本节代码地址
1.Hystrix 的简单实用
下面我们通过新建项目一步一步进入Hystrix 的篇章。
1.1 新建项目
此项目是不在Spring Cloud下运行的,仅仅演示Hystrix的特性,后续会专门讲解和Spring Cloud的使用。
1.2 添加Maven配置
<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>
1.3 新建HystrixCommand 类
下面我们编写一个HystrixCommand的实现类,通过设置一个Groupkey。具体的逻辑卸载run()方法中,并在方法中输出当前的线程名,本节我们都将通过main()方法调用。
命令组名称(Groupkey) 是必传的,默认情况下全局维护的线程池
Map以该值作为Key,该Map的Value为执行命令的线程池。
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) throws ExecutionException, InterruptedException {
Future<String> test = new FwHystrixCommond("test").queue();
System.out.println(test.get());
}
}
右键运行之后,可以看到正常的输出,并且我们的组名变成了线程的名字
test:hystrix-myGroup-1

