springcloud之Hystrix初识篇—结合ResTeamplate小述
【PS:观看该篇文章前请先参考上一篇文章】
捕获熔断异常:降级方法中可以添加一个异常参数,用于抓取正式调用请求异常的信息。
/**
* fallbackMethod:降级方法【PS:该方法最多只能添加下面这2个参数,或只接收请求方法的参数】
* @param body 请求方法的参数
* @param throwable 异常信息
* @return
*/
public String sendFail(String body,Throwable throwable){
logger.info("异常信息:"+throwable);
//备用逻辑
return "restTemplate熔断:"+body;
}
再次请求:
ResTeamplate请求的熔断节点:
根据之前的描述可以分析到消费者调用提供者,提供者服务异常消费者执行熔断操作,所以是提供者异常执行的熔断?
示例1:
提供者:
@RequestMapping("/hystrixRestTemplate/Code")
public String hystrixRestTemplateSend(@RequestBody String body){
System.out.println(body);
String[] str = new String[3];
//数组越界
System.out.println(str[3]);
return port+":"+body;
}
消费者调用:
控制台打印异常:请求返回:
总结:提供者服务异常,消费者执行熔断操作
示例2:
前提:提供者正常。
消费者:
@HystrixCommand(fallbackMethod="sendFail")
public String hystrixRestTemplateSend(String body) {
String url = "http://test1/eureka-clinet1/hystrixRestTemplate/Code";
ResponseEntity<String> result = restTemplate.postForEntity(url,body,String.class);
System.out.println("提供者返回结果:"+result);
try {
//线程睡眠时间过长,即使服务提供者返回正常方法也会熔断
Thread.sleep(10000);
}catch (Exception e){
}
return result.getBody();
//return "test";
}
调用请求:
控制台信息:
请求返回信息:
原因:控制台打印出一个异常HystrixTimeoutException,因为在提供者返回结果后我们让线程sleep10秒,导致熔断器认为方法超时自动执行了熔断操作,走了降级方法。
总结:RestTemplate调用模式中熔断节点在被@HystrixCommand所修饰的方法,而不是被**调用的**提供者方法。
还没有评论,来说两句吧...