Feign调用返回值统一处理

因为接口一般有固定的返回格式,有数据、返回码和异常时错误信息。

不做任何处理情况下,需要在调用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 {
    private Gson gson = new Gson();

    @Autowired
    private ObjectFactory messageConverters;

    private ResponseEntityDecoder responseEntityDecoder;

    @Override
    public Object decode(final Response response, Type type) throws IOException,
            FeignException {
        Object result = responseEntityDecoder.decode(response, type);
        XXXResponseResult baseResponse = (XXXResponseResult ) result;
        //XXXResponseResult baseResponse = gson.fromJson(response.body().asReader(), XXXResponseResult .class);

        int code = baseResponse.getResultCode();
        if (code == 0) {
            return result;
        }
        log.error("远程调用失败:{}", baseResponse);
        throw new XXXException("远程调用失败");
    }

    @Override
    public void afterSingletonsInstantiated() {
        //初始化spring提供的解析器
        responseEntityDecoder = new ResponseEntityDecoder(new SpringDecoder(this.messageConverters));
    }
}

修改配置类

@Configuration
public class FeignConfig {

    @Bean
    public Decoder feignDecoder() {
        return new FeignDecode();
    }
}

解决方法2

添加接口类,对feign结果进行进一步处理。

@Component
public class FeignServiceFacade {

    @Autowired
    private XXXFeign xxxFeign;
    
    public List getXXXList(List ids) throws XXXException {
        XXXResponseResult> xxxResponseResult = zhyqSysBasicFeign.pntValList(ids);
        if(xxxResponseResult.getResultCode()== ResponseResult.SUCCESS){
            return xxxResponseResult.getData();
        }
        throw new XXXException("error");

    }
}

参考

Fegin 中统一处理调用的结果_openfeign统一处理返回结果-CSDN博客

Feign返回值统一处理_feign返回结果统一处理-CSDN博客

你可能感兴趣的:(#,springCloud,java)