在不少系统架构中都须要考虑横向扩、单点故障等问题,对于一个庞大的应用集群,部分服务或者机器出现问题不可避免,在出现故障时,如何减小故障的影响、保障集群的高可用,成为一个重要的工做,Hystrix 是一个帮助解决分布式系统交互时超时处理和容错的类库,它一样拥有保护系统的能力。Hystrix 主要实现如下功能: apache
Hystrix 使用示例 网络
建立Maven项目,命名为 hystrix-client,并增长 hystrix 依赖和 Http 提交相关依赖,POM.xml 内容以下:架构
<?xmlversion="1.0"encoding="UTF-8"?>maven
<projectxmlns="http://maven.apache.org/POM/4.0.0" 分布式
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ide
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd"> 测试
<modelVersion>4.0.0</modelVersion> this
<groupId>org.lixue</groupId>url
<artifactId>hystrix-client</artifactId> spa
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--Hystrix依赖-->
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.12</version>
</dependency>
<!--logback日志依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!--http客户端依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
</dependencies>
</project>
命令类须要继承 HystrixCommand 类,并实现其 run 方法执行具体业务,实现 getFallback 方法执行回退业务,在调用 run 方法超时或者断路器处于打开状态时,会调用 getFallback 方法进行回退。
package org.lixue.hystrixclient;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SpeakSleepCommand extends HystrixCommand<String>{
private int sleep;
private CloseableHttpClient httpClient;
private String url;
public SpeakSleepCommand(intsleep){
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Speak"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()));
this.sleep=sleep;
this.httpClient=HttpClients.createDefault();
this.url="http://localhost:8080/speak/sleep?seconds="+this.sleep;
}
protected String run() throws Exception{
try{
HttpGet request=new HttpGet(this.url);
HttpResponse response=httpClient.execute(request);
return EntityUtils.toString(response.getEntity());
}catch(Exceptionex){
ex.printStackTrace();
return ex.getMessage();
}
}
@Override
protected String getFallback(){
return"call fallback";
}
}
实例化咱们建立的 SpeakSleepCommand 类,并调用 execute 来执行(调用 run 方法不会使用 Hystrix)
package org.lixue.hystrixclient;
public class HystrixClient{
public static void main(String[]args){
SpeakSleepCommand cmd=new SpeakSleepCommand(10);
try{
Stringresult=cmd.execute();
System.out.println("请求结果="+result);
}catch(Exceptionex){
ex.printStackTrace();
}
}
}
默认状况下,Hystrix 是 1000 毫秒超时,咱们在实例化传入的是10秒,所以在调用的时候会执行 getFallback 方法;若是修改在实例化传入 0 秒,不进行阻塞,会正常返回结果值。