Feign和Hystrix异常熔断的理解

使用Feign client进行restful服务间的调用,除了要注意超时时间、retry的设置外,还有一个关于自定义异常的部分,需要注意一下,不然容易出错。
以下Feign处理请求返回的关键代码,由此可知Feign将Http状态码大于等于200且小于300且不等于404的返回当成服务异常进行处理了,如果抛出FeginException,那么Hystrix就会去调用fallback方法(如果没有,则抛出HystrixRuntimeException,有则正常调用)。
if(response.status() >= 200 && response.status() < 300) {
    if(Void.TYPE == this.metadata.returnType()) {
        e = null;
        return e;
    }
    e = this.decode(response);
    return e;
}
if(!this.decode404 || response.status() != 404) {
    throw this.errorDecoder.decode(this.metadata.configKey(), response);
}
e = this.decoder.decode(response, this.metadata.returnType());
public Exception decode(String methodKey, Response response) {
    FeignException exception = FeignException.errorStatus(methodKey, response);
    Date retryAfter = this.retryAfterDecoder.apply((String)this.firstOrNull(response.headers(), "Retry-After"));
    return (Exception)(retryAfter != null?new RetryableException(exception.getMessage(), exception, retryAfter):exception);
}
但是,由于项目中要求严格遵循restful架构风格,那么,出现业务异常时也不能返回200,而可能是400等,那么其实我们想要的是出现业务异常应直接返回给前端,不应该调用fallback方法,所以我们要修改Feign处理错误的地方,如下:
package com.sunlight.platform.exception;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 业务异常处理
 * @author niufan
 */
@Component
public class BusinessExceptionFeignErrorDecoder extends ErrorDecoder.Default {

    @Value("${bad.request.error.codes:B}")
    private String badRequestErrorCodes;
    @Value("${bad.request.error.code.prefixes:B}")
    private String badRequestErrorCodePrefixes;

    @Override
 public Exception decode(String methodKey, Response response) {
        Exception exception = null;
        String body = null;
        try {
            body = Util.toString(response.body().asReader());
        } catch (IOException e) {
            exception = e;
        }
        if (body != null) {
            ResponseData responseData = JSON.parseObject(body, ResponseData.class);
            String errorCode = String.valueOf(responseData.getErrorCode());
            if (StringUtils.hasText(errorCode)) {
                if (badRequestErrorCodes.contains(errorCode)) {
                    exception = new HystrixBadRequestException(body);
                } else {
                    List<String> badRequestErrorCodePrefixList = Arrays.asList(badRequestErrorCodePrefixes.split("\\|"));
                    if (!CollectionUtils.isEmpty(badRequestErrorCodePrefixList)) {
                        for (String badRequestErrorCodePrefix: badRequestErrorCodePrefixList) {
                            if (errorCode.startsWith(badRequestErrorCodePrefix)) {
                                exception = new HystrixBadRequestException(body);
                                break;
                            }
                        }
                    }
                }
            }
        }
        if (exception == null) {
            exception = super.decode(methodKey, response);
        }
        return exception;
    }
}
 当Feign去处理异常时,会调用以上我们重写的方法,思路:如果返回异常的Http状态,那么我们取得返回体里内容,根据errorCode判断是否需要进入直接返回bad request。
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值