spring cloud hystrix 使用详解

  • 通过@HystrixCommand注解定义Hystrix命令的实现,实现异步执行的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public String () {
Future<String> future = new AsyncResult<String>() {
@Override
public String invoke() {
return restTemplate.getForEntity("http://XXXX/hello",String.class).getBody();
}
};
String result = null;
try {
result = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return result;
}
  • 忽略指定异常类型,不触发后续的fallback逻辑:
1
2
3
4
5
(ignoreExceptions = {HystrixBadRequestException.class})
public void helloServicea() {
}
  • 在fallback实现方法的参数中增加Throwable e对象的定义,在方法内部获取触发服务降级的具体异常内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
public String helloFallBackExceptionCheck(Throwable e) {
if (e instanceof RuntimeException) {
System.out.println("has RuntimeException.");
}
String info = "";
if (e.getMessage() != null) {
info = "has exception:" + e.getMessage();
} else {
info = "read time out.";
}
return info;
}
  • 设置命令名称、分组以及线程池划分,配置资源隔离:
1
2
3
4
5
(commandKey = "helloService",groupKey = "helloGroup",threadPoolKey = "helloThread")
public void helloServicea() {
}