当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Cloud Hystrix异常处理方法详解

Spring Cloud Hystrix异常处理方法详解

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了spring cloud hystrix异常处理方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

在调用服务执行hsytrixcommand实现的run()方法抛出异常时,除hystrixbadrequestexception之外,其他异常都会认为是hystrix命令执行失败并触发服务降级处理逻辑.

异常处理

当hystrix命令因为异常(除了hystrixbadrequestexception异常)进入服务降级逻辑之后,往往需要对不同的异常做针对处理,那么就要捕获异常。对于使用@hystrixcommand注解只需要在降级函数中增加throwable e对象的定义

/**
* hystrixbadrequestexception:
* 与由hystrixcommand抛出的所有其他异常不同,这不会触发回退,也不会对失败度量进行计数,因此不会触发断路器。
* @return
*/
@hystrixcommand(fallbackmethod="hellobackmethodfirst",ignoreexceptions=hystrixbadrequestexception.class)
public string helloservice() {
logger.info("start invoke service");
//uri需要使用虚拟主机名(即服务名称,而不是主机名)
//return resttemplate.getforentity("http://service-provide/hello", string.class).getbody();
throw new runtimeexception("consumer exception");
}
/**
* 通用降级函数
* @return
*/
@hystrixcommand(fallbackmethod="hellobackmethodsecond")
public string hellobackmethodfirst(throwable e){
/*
* 一些异常判断
* if(e instanceof checkeception){
* }
* if(e instanceof illegalstateexception){
* }
*/
//此处可能是另外一个网络请求,所以也可能出现错误
return "error1:"+e.getmessage();
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网