前言
如果想在服务中加入一种中断异常服务并可以快速响应的功能的话,使用Feign集成的Hystrix是一个还不错的选择。
一、OpenFeign对Hystrix的支持
要让hystrix生效,需要开启feign.hyxtrix
。开启了feign.hystrix
之后,feign就会用断路器包裹所有的方法,对这些方法起保护作用,通过回退方法把异常信息反馈回去。
二、配置
1. yml的配置
1.1 启用feign的hystrix,令其生效
feign:
hystrix:
enabled: true
1.2 在配置一下超时
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 60000
2. Hystrix的回退
hystrix的回退有两种一种是带异常信息的,一种是不带异常信息的。对于这种不带异常信息的应该用的不多,下边的示例是带有异常信息的。
代码如下(示例):
import com.test.backend.common.domain.CommonResult;
import com.test.backend.common.domain.Payment;
import com.test.springcloud.feign.api.PaymentServiceFeign;
import feign.FeignException;
import feign.RetryableException;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
@Component
public class PaymentServiceFeignFallbackFactory implements FallbackFactory<PaymentServiceFeign> {
@Override
public PaymentServiceFeign create(Throwable throwable) {
return new PaymentServiceFeign() {
@Override
public CommonResult<Payment> getPaymentById() {
CommonResult commonResult = new CommonResult();
commonResult.setMsg(throwable.getMessage());
// 对方服务没启动
if (throwable instanceof FeignException.ServiceUnavailable) {
System.out.println("对方服务不可用");
// 对方服务报错了
} else if (throwable instanceof FeignException.InternalServerError){
System.out.println("对方服务内部异常");
// 对方服务启后又关了
}else if( throwable instanceof RetryableException) {
System.out.println("对方服务重试后无法连接");
}
return commonResult;
}
};
}
}
回退类编写完毕后,需要在FeignClient
上配置一下
@FeignClient(value = "backend-service", contextId = "backend-service-1", fallbackFactory = PaymentServiceFeignFallbackFactory.class)
三、 效果
emmmm,好像也没啥可以展示的效果图,自己写写代码感受感受就完事了。
总结
feign提供的Hystix断路保护功能,能够大大的提升了服务的稳定性,毕竟没那么多的异常了,当使用feign访问的远程服务有异常时,通过回退类做一些明确的响应提示或者其他的处理还是挺不错的。
印象中Hystrix有个单独的包,还有挺多的参数,有空在研究一下…