關於springcloud中使用feign出現LinkedHashMap can not be cast to xxx 的解決方案
阿新 • • 發佈:2018-12-02
關於springcloud中使用feign出現LinkedHashMap can not be cast to xxx 的解決方案
個人公眾號
扯淡
- 博主遇到這個問題也很久了,在網上也看了沒找到解決方案,一直沒時間去解決,最近稍微抽了一點時間研究了一下,分享出來造福眾多的碼農朋友,feign預設是根據返回的資料解析為LinkedHashMap這種key value的格式,但是我們專案中一般會有自定義的Result<T,E>這樣的複雜型別的物件,這樣的話,feign就不能像dubbo這樣的rpc那樣得到我們自己想要的Result<T,E>物件,下面是解決方案:
解決方案 自定義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);
}
最後
開始愉快的擼碼吧 !