由feign調用報錯引起的分析和調試

認證項目的 feign調用用戶服務出現的錯誤:

Caused by: org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.x.y.MsgResult] and content type [application/octet-stream]
  1. 根據上面的錯誤可以瞭解到feign 客戶端發起RestTemplate的請求後返回的響應是沒有合適的http消息轉換器導致的。
    也就是響應內容返回的類型採用的默認[application/octet-stream]
  2. 但是服務提供的地址url,確認已經配置了對應的響應類型 。
@RequestMapping(value = "/user/info/v1", method = { RequestMethod.POST },produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {MediaType.APPLICATION_JSON_VALUE})
  1. 也就是設置的響應編碼類型,無法匹配的到合適的解碼轉換器 ** (匹配不到就會採用@FeignClientsConfiguration的默認解碼器 )**。這個原因可以進行斷點調試,發現沒有調用到上面的服務url; 而是直接網關層攔截攔截返回了,原因網關層直接做了url的白名單過濾。這就是導致無法調用到上面的服務url的正在原因。

解決方案:

  1. 配置網關層白名單,讓請求正常調用服務提供的url;
  2. 覆蓋@FeignClientsConfiguration 的默認解碼器; 可以正常處理網關的響應類型;【響應結果:白名單過濾驗證失敗,還是要配置網關層白名單】
@Configuration
public class FeignConfiguration {
    @Bean
    public Decoder feignDecoder() {
        HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
        return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
    }
}

// @FeignClient 引用即可
@FeignClient(name="UserFeignClient",configuration = FeignConfiguration.class)

擴展1:spring官網文檔

https://cloud.spring.io/spring-cloud-static/spring-cloud-openfeign/2.2.3.RELEASE/reference/html/#spring-cloud-feign-overriding-defaults

擴展2:常用的一些消息轉換器

2.1. The Default Message Converters

By default, the following HttpMessageConverters instances are pre-enabled:

  • ByteArrayHttpMessageConverter – converts byte arrays
  • StringHttpMessageConverter – converts Strings
  • ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
  • SourceHttpMessageConverter – converts javax.xml.transform.Source
  • FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.
  • Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)
  • MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)*
    *
  • MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)
  • AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)
  • RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章