关于springcloud中使用feign出现LinkedHashMap can not be cast to xxx 的解决方案

扯淡

  • 博主遇到这个问题也很久了,在网上也看了没找到解决方案,一直没时间去解决,最近稍微抽了一点时间研究了一下,分享出来造福众多的码农朋友,feign默认是根据返回的数据解析为LinkedHashMap这种key value的格式,但是我们项目中一般会有自定义的Result这样的复杂类型的对象,这样的话,feign就不能像dubbo这样的rpc那样得到我们自己想要的Result对象,下面是解决方案:

个人公众号

个人公众号

解决方案 自定义FeignClient,覆盖提供的FeignClient

@Configuration
public class FeignConfig {

   @Bean
   public Decoder feignDecoder() {
       HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper());
       ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
       return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
   }
   @Bean
   public Encoder feignEncoder(){
       HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper());
       ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
       return new SpringEncoder(objectFactory);
   }
   public ObjectMapper objectMapper(){
       ObjectMapper objectMapper = new ObjectMapper();
       objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
       return objectMapper;
   }
}
  • 再附上一段调用的代码 ,需要注意的是在接口上必须加上你需要转化的结果,不然还是 LinkedHashMap
@FeignClient(value = "xxx-service",fallback = UserFacadeFallback.class)
@Component
public interface UserFacade {
    @RequestMapping(value = "/user", method = {RequestMethod.POST})
    UserResponse<EnumGeneralResultCode,UserDto> getUserDto(@RequestBody UserDto user);
}

最后

开始愉快的撸码吧 !

你可能感兴趣的:(springcloud微服务)