OpenFeign(四)

实现解码器Decoder 接口

public class FeignResultDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (ObjectUtils.isEmpty(response.body())) {
            throw new DecodeException(response.status(), "无数据", response.request());
        }
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //对结果进行转换
        Result result = null;
        try {
            result = (Result) mapper.readValue(bodyStr, mapper.getTypeFactory().constructParametricType(Result.class, Class.forName(type.getTypeName())));
        } catch (ClassNotFoundException e) {
            throw new DecodeException(response.status(), "接口返回错误:" + result.getMsg(), response.request());
        }
        //如果返回错误,且为内部错误,则直接抛出异常
        if (!result.getSuccess()) {
            throw new DecodeException(response.status(), "接口返回错误:" + result.getMsg(), response.request());
        }
        return result.getData();
    }
}

配置为全局解码器

@Configuration
public class FeignConfig {
    @Bean
    public Decoder feignDecoder() {
        return new FeignResultDecoder();
    }
}

服务接口抽取为API模块,service供内部服务使用,api通过网关暴露给外部服务
OpenFeign(四)

上一篇:SpringCloud Hoxton版 + SpringCloud alibaba学习笔记(4)-- OpenFeign服务接口调用


下一篇:填坑系列之OpenFeign