0


OpenFeign 自定义结果转换

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> 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<TestDto> getById(@RequestBody RequestDto<TokenDto> requestDto);
}

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

注意:

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

标签: java 前端 json

本文转载自: https://blog.csdn.net/qq_34484062/article/details/129088354
版权归原作者 飘零未归人 所有, 如有侵权,请联系我们删除。

“OpenFeign 自定义结果转换”的评论:

还没有评论