微服务Feign组件远程调用自定义解码器
微服务Feign组件远程调用自定义解码器
·
Feign远程调用响应结果格式
public class Result<T> {
/**
* 响应码,200为成功
*/
private Integer code;
/**
* 响应信息
*/
private String message;
/**
* 响应的具体对象
*/
private T data;
}
自定义Feign解码器
@Component // 注入Spring的IOC容器中,所有的Feign远程调用响应生效
public class FeignResultDecoder implements Decoder {
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
if (response.body() == null) {
throw new DecodeException(response.status(), "未返回正确的数据", response.request());
}
String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
// TODO 进行转换(jackson提供json2obj方法实现Result转换)
Result result = (Result) JsonUtil.json2obj(bodyStr, type);
// TODO 最终响应结果为Result中的泛型对象
return result.data;
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)