因为接口一般有固定的返回格式,有数据、返回码和异常时错误信息。
不做任何处理情况下,需要在调用Feign的业务代码处通过判断返回码来获取数据。这种重复的代码可以抽出来统一处理。
解决方法1
使用自定义Decoder来统一处理,重写Object decode(Response response, Type type)方法。
自定义解析类
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;import java.io.IOException;
import java.lang.reflect.Type;@Slf4j
public class FeignDecode implements Decoder, SmartInitializingSingleton {@Autowiredprivate ObjectFactory<HttpMessageConverters> messageConverters;private ResponseEntityDecoder responseEntityDecoder;@Overridepublic Object decode(final Response response, Type type) throws IOException,FeignException {Object result = responseEntityDecoder.decode(response, type);XXXResponseResult baseResponse = (XXXResponseResult ) result;int code = baseResponse.getResultCode();if (code == 0) {return result;}log.error("远程调用失败:{}", baseResponse);throw new XXXException("远程调用失败");}@Overridepublic void afterSingletonsInstantiated() {//初始化spring提供的解析器responseEntityDecoder = new ResponseEntityDecoder(new SpringDecoder(this.messageConverters));}
}
修改配置类
@Configuration
public class FeignConfig {@Beanpublic Decoder feignDecoder() {return new FeignDecode();}
}
解决方法2
添加接口类,对feign结果进行进一步处理。
@Component
public class FeignServiceFacade {@Autowiredprivate XXXFeign xxxFeign;public List<XXXVo> getXXXList(List<Long> ids) throws XXXException {XXXResponseResult<List<XXXVo>> xxxResponseResult = zhyqSysBasicFeign.pntValList(ids);if(xxxResponseResult.getResultCode()== ResponseResult.SUCCESS){return xxxResponseResult.getData();}throw new XXXException("error");}
}
参考
Fegin 中统一处理调用的结果_openfeign统一处理返回结果-CSDN博客
Feign返回值统一处理_feign返回结果统一处理-CSDN博客