spring-cloud feigin发送请求参数需要进行驼峰和下划线的转换

spring-cloud feigin发送请求参数需要进行驼峰和下划线的转换

背景

项目改造为sping-cloud, 依赖别人的feign(fei-api)服务,使用feign发送请求的时候,对方接口参数和返回值都是下划线类型的,所以需要把请求参数和返回值转换为驼峰类型

解决过程

1:使用spring的spring.jackson.property-naming-strategy 配置,
引起的问题,自己的接口和返回值会将驼峰转换为下划线,所以忽略
2:因为这边的feign-api中的参数都是对象,所以新建一个参数的子类加上@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)注解,传参数的时候使用子类,完美解决,但是新建子类返回值下划线/驼峰转换失败

解决方案

@EnableFeignClients加上encode和decode @EnableFeignClients(defaultConfiguration ={FeignClientEncoder.class,FeignClientEncoder.FeignClientDecoder.class})

public class FeignClientEncoder extends SpringEncoder {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    }

    public FeignClientEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters);
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {

        try {
            super.encode(object, bodyType, template);
            template.body(objectMapper.writeValueAsString(object));
        } catch (Exception ex) {

        }

        System.out.println();
    }

    public static class FeignClientDecoder extends SpringDecoder {
        public FeignClientDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
            super(messageConverters);
        }

        @Override
        public Object decode(Response response, Type type) throws IOException, FeignException {
            String result = response.body().toString();
            if (type instanceof Class && StringUtils.isNoneBlank(result)) {
                Response build = Response.builder()
                        .body(new ObjectMapper().writeValueAsString(objectMapper.readValue(result, (Class<? extends Object>) type)), Charset.defaultCharset())
                        .headers(response.headers())
                        .reason(response.reason())
                        .status(response.status())
                        .request(response.request())
                        .build();
                return super.decode(build, type);
            }
            return super.decode(response, type);
        }
    }
}

原文:https://blog.csdn.net/weixin_43455403/article/details/108537342
作者: 走着路睡觉