- 时间:2022-08-20 00:52 编辑: 来源: 阅读:273
- 扫一扫,手机访问
摘要:春云OpenFeign设置自己的结果解码器。
{导航网站源码}
我们在定义微服务接口的时候,一般会用一个结果类来封装,它把提醒信息、返回对象和状态码封装在一起,返回给调用者,比如下面的格式:public class result 为了实现上述功能,我们需要修改默认的解码器。 Cloud Open Feign允许我们在定义一个Feign客户端时指定一个额外的配置类,例如:@FeignClient(name = "stores ",Configuration = customized Configuration . class)公共接口store client {//..}而这个配置类可以作为我们的扩展点。我们可以在自定义配置中定义自己的解码器来覆盖默认配置。 Cloud对Feign的封装和默认配置可以在官方文档中查看。 您设置的解码器需要实现feign.codec.Decoder接口,也可以参考默认解码器的实现逻辑(org . spring framework . cloud . open feign . support . response entitydecoder)。下面的实现可以拆分统一返回值结果类,解决异常返回:公共类feignresultdecoder实现decoder { @ override public object decode(response response,type type) throws io exception,DecodeException,feigne exception { if(response . body()= = null){ throw new decode exception(response . status(),“没有返回有效数据”,response . request());} String body str = util . tostring(response . body()。asReader(Util。UTF _ 8));//转换结果result =(result)JSON util . JSON 2 obj(body str,type);//如果返回错误,而且是内部错误,会直接抛出异常if (result.getCode())!=结果代码。SUCCESS.code) { if(!result . isuser prompt(){ throw new decode exception(response . status(),”接口返回错误:“+result.getmessage()、response . request()”;} }返回result.data}}}如何将response中的json转换成实际的返回类型需要一点功夫。由于可能的复杂嵌套关系和通用定义,最终发现jackson框架已经有了一个默认的实现...代码如下:public static