springcloud openfeign 解析泛型

版本

springboot 2.5.5
spring cloud 2020.0.4

问题

使用feign返回值为泛型时不能正确解析

解决

  • 自定义解析器
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.core.NamedThreadLocal;

import java.io.IOException;
import java.lang.reflect.Type;

public class GenericsResultDecoder extends SpringDecoder {
    private static NamedThreadLocal<Type> resultTypeThreadLocal = new NamedThreadLocal<>("feignResultType");

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

    public static void setFeignReturnType(Type feignReturnType) {
        resultTypeThreadLocal.set(feignReturnType);
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        Type resultType = resultTypeThreadLocal.get();
        resultTypeThreadLocal.remove();
        if (resultType == null) {
            resultType = type;
        }
        return super.decode(response, resultType);
    }
}
  • 注册解析器
@Bean
public Decoder feignDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
    return new OptionalDecoder(new ResponseEntityDecoder(new GenericsResultDecoder(messageConverters)));
}
  • 调用时先设置返回类型
GenericsResultDecoder.setFeignReturnType(TypeUtils.parameterize(Page.class, MyEntity.class));
Page<MyEntity> page = feignClient.findAll();
        

源码

  • 默认feign自动配置-默认解析器
    org.springframework.cloud.openfeign.FeignClientsConfiguration
@Bean
@ConditionalOnMissingBean
public Decoder feignDecoder() {
	return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
}

posted on 2022-04-11 22:38  路过君  阅读(721)  评论(0编辑  收藏  举报

导航