OpenFeign 自定义结果转换

您所在的位置:网站首页 menuindex未定义 OpenFeign 自定义结果转换

OpenFeign 自定义结果转换

2023-03-11 02:02| 来源: 网络整理| 查看: 265

Spring Cloud OpenFeign定义的客户端调用远程服务时,默认的解码器只能按照定义的方法返回类型对接口的返回结果进行强制转换,没办法实现一些自定义的逻辑,比如将统一返回的Result类重新拆开,仅返回对应的业务对象,或者对特定的响应码进行处理等等。

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)); if(StringUtils.isNotEmpty(bodyStr)){ //对结果进行转换 Result result = FeignResultDecoder.json2obj(bodyStr, type); 可以处理成自己需要返回的类 return result; } return null; } public static T json2obj(String jsonStr, Type targetType) { try { JavaType javaType = TypeFactory.defaultInstance().constructType(targetType); return new ObjectMapper().readValue(jsonStr, javaType); } catch (IOException e) { throw new IllegalArgumentException("将JSON转换为对象时发生错误:" + jsonStr, e); } } }

config配置:

实现了Decoder之后,只需要将其配置到CustomizedConfiguration中即可,注意如果CustomizedConfiguration添加了@Configuration的注解,则会成为Feign Client构建的默认配置,这样就不需要在每个@FeignClient注解中都去指定配置类了:

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

在对应的feign上做计入处理

@FeignClient(name = "TestFeign ", configuration = CustomizedConfiguration.class, fallback = TestFeign FallBack.class) public interface TestFeign { @GetMapping("/getById") BaseResponseDto getById(@RequestBody RequestDto requestDto); }

类似的方式,我们还可以自定义Feign的Encoder,ErrorDecoder等关键配置组件。

注意:

        这种配置的方式仅限于用注解@EnableFeignClients("xxxx")自动扫描的类@FeignClient注解,如果我们是使用FeignClientBuilder自定义返回的就无法使@FeignClient中的配置name,configuration,url等配置自动生效。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3