Feign发送Get请求时,采用POJO对象传递参数的最终解决方案

转载自:https://blog.csdn.net/f641385712/article/details/82431502

叙述

spring cloud技术栈里面,Feign 可以使得我们的rest调用和调用本地方法一样方便。但是它真的有非常多的坑,苦不堪言啊。本文将描述我们最为常遇到的坑:

异常

Feign发送 Get 请求时,采用POJO传递参数,报异常

Request method ‘POST’ not supported

@FeignClient("microservice-provider-user")
public interface UserFeignClient {

  @RequestMapping(value = "/user", method = RequestMethod.GET)
  public PageBean get(User user);
  
}
feign.FeignException: status 405 reading UserFeignClient#get0(User); content:
{"timestamp":1482676142940,"status":405,"error":"Method Not Allowed", "exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/user"}

于是就开始逐行调试,知道我从feign的源码中发现了这个:

private synchronized OutputStream getOutputStream0() throws IOException {
  try {
      if(!this.doOutput) {
            throw new ProtocolException("cannot write to a URLConnection if doOutput=false - call setDoOutput(true)");
 } else {
      if(this.method.equals("GET")) {
           this.method = "POST";
 }

这段代码是在  HttpURLConnection  中发现的,jdk原生的http连接请求工具类,原来是因为Feign默认使用的连接工具实现类,所以里面发现只要你有body体对象,就会强制的把get请求转换成POST请求。

终上所述,这也不能怪feign,是HttpURLConnection 的问题。所以接下来我准备换一个 HttpClient 试试,因此本利我采用apache的HttpClient。但是一定,一定需要加入如下几个步骤:

开启熔断,替换 HttpURLConnection 为 HttpClient

# 开启断路器功能, feign默认该功能关闭
feign:
  # 启用熔断器
  hystrix:
    enabled: true
  # httpclient 替换 HttpURLConnection
  httpclient:
    enabled: true

在依赖中引入apache的httpclient


 org.apache.httpcomponents
 httpclient
 4.5.3

启用feign-httpclient


    com.netflix.feign
    feign-httpclient
    8.15.0

修改feign

@GetMapping(value = "/queryAllEquipments", consumes = MediaType.APPLICATION_JSON_VALUE)

PageBean queryAllEquipments(
    @RequestHeader(value = "Authorization") String token, 
    @RequestBody QueryAllEquipmentsVO vo
);

注意这里的 consumes = MediaType.APPLICATION_JSON_VALUE

这个是设置请求数据格式为 application/json,应为feign默认格式为 text/html。如果不写,则请求失败被熔断返回null

你可能感兴趣的:(Spring相关)