栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springcloud openfeign 解析泛型

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 resultTypeThreadLocal = new NamedThreadLocal<>("feignResultType");

    public GenericsResultDecoder(ObjectFactory 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 messageConverters) {
    return new OptionalDecoder(new ResponseEntityDecoder(new GenericsResultDecoder(messageConverters)));
}
  • 调用时先设置返回类型
GenericsResultDecoder.setFeignReturnType(TypeUtils.parameterize(Page.class, MyEntity.class));
Page page = feignClient.findAll();
        
源码
  • 默认feign自动配置-默认解析器
    org.springframework.cloud.openfeign.FeignClientsConfiguration
@Bean
@ConditionalOnMissingBean
public Decoder feignDecoder() {
	return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/680547.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号