由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.
  • 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)

你可能感兴趣的:(源码研究,微服务架构,springcloud)