HyStrix 精华提炼

最近在学些springcloud 相关的东西,看到hystrix的相关内容,觉得非常有用,在此记录一下。

hystrix(容断器    具有容错和断路的功能)

需要说的一点是 hystrix 是作用在调用者一方的组件,与被调用者无关

下面直接上代码:

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

// httpclient 包是为了测试时使用的。

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

下面上server端得代码:

@RestController
public class MyController {

    @GetMapping("/normalHello")
    public String normalHello(HttpServletRequest request) {
        return "Hello World";
    }
    
    @GetMapping("/errorHello")
    public String errorHello(HttpServletRequest request) throws Exception {
        // 模拟需要处理10秒
        Thread.sleep(10000);
        return "Error Hello World";
    }
}

server端简单的提供了2个方法。一个为正常返回的,一个为模拟程序出现延迟的情况。

client端得代码首先需要继承 HyStrixCommand<> 并实现其 run() 方法,如果需要用到短路处理,则还需要实现getFallback() 方法,短路处理方案的代码放在此方法中。

public class HelloCommand extends HystrixCommand<String> {

	private String url;
	
	CloseableHttpClient httpclient;
	
	public HelloCommand(String url) {
		// 调用父类的构造器,设置命令组的key,默认用来作为线程池的key
		super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
		// 创建HttpClient客户端
		this.httpclient = HttpClients.createDefault();
		this.url = url;
	}
	
	protected String run() throws Exception {
		try {
			// 调用 GET 方法请求服务
			HttpGet httpget = new HttpGet(url);
			// 得到服务响应
			HttpResponse response = httpclient.execute(httpget);
			// 解析并返回命令执行结果
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	protected String getFallback() {
		System.out.println("执行 HelloCommand 的回退方法");
		return "error";
	}
	
}

接下来我们在client 中写两个测试方法测试一下。

        // 访问server端异常方法	
        public static void main(String[] args) {
		// 请求异常的服务
		String normalUrl = "http://localhost:8080/errorHello";
		HelloCommand command = new HelloCommand(normalUrl);
		String result = command.execute();
		System.out.println("请求异常的服务,结果:" + result);
	}
        
	public static void main(String[] args) {
		// 请求正常的服务
		String normalUrl = "http://localhost:8080/normalHello";
		HelloCommand command = new HelloCommand(normalUrl);
		String result = command.execute();
		System.out.println("请求正常的服务,结果:" + result);
	}

从测试结果中我们看出当我们请求错误server时 接口访问超过hystrix 默认超时时间后,hystrix 自动抵用getFallback()方法执行

,如果我们不实现HyStrixCommand<> 中的getFallback 方法那么 接口访问超时时hystrix 会爆出异常。

hystrix 命令执行过程:

HyStrix 精华提炼

断路器开启:

整个链路达到一定的阈值,默认情况下,10S内产生超过20次请求,则符合第一个条件,

在满足第一个条件的基础上,如果请求的错误数大于阈值,则会打开断路器,默认50%

短路器开启后,进入休眠期,默认5S,5S尝试性执行一次命令,如果成功则断路器关闭,失败则断路器仍然继续打开。

 

隔离策略

 thread  (线程池)

semaphore(信号量,不支持超时和异步策略)

hystrix 缓存功能 (一次请求)可以实现 getCacheKey() 方法来实现