Spring Boot 和 Spring Cloud Feign调用服务及传递参数踩坑记录
阅读原文时间:2022年03月23日阅读:1

背景 :在Spring Cloud Netflix栈中,各个微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端。我们可以使用JDK原生的URLConnection、Apache的Http Client、Netty的异步HTTP Client, Spring的RestTemplate。但是,用起来最方便、最优雅的还是要属Feign了。Feign是一种声明式、模板化的HTTP客户端。

  Contronller层通过feignClient调用微服务 获取所有任务

@Controller
@RequestMapping("tsa/task")
public class TaskController{
@Autowired
TaskFeignClient taskFeignClient;

@PostMapping("/getAll")  
@ResponseBody  
public List<TaskVO> getAll() {  
    List<TaskVO> all = taskFeignClient.getAll();  
    return all;  
}  

}

  @FeignClient用于通知Feign组件对该接口进行代理(不需要编写接口实现),使用者可直接通过@Autowired注入。

Spring Cloud应用在启动时,Feign会扫描标有@FeignClient注解的接口,生成代理,并注册到Spring容器中。生成代理时Feign会为每个接口方法创建一个RequetTemplate对象,该对象封装了HTTP请求需要的全部信息,请求参数名、请求方法等信息都是在这个过程中确定的,Feign的模板化就体现在这里。

@FeignClient(qualifier = "taskFeignClient", name = "service-tsa",fallback = TaskFeignClientDegraded.class)
public interface TaskFeignClient {
@PostMapping(value = "taskApiController/getAll")
List getAll();

}

  微服务端

@Slf4j
@RestController
@RequestMapping("taskApiController")
public class TaskApiController{

@Autowired  
private TaskService taskService;

@PostMapping("/getAll")  
public List<TaskVO> getAll() {  
    log.info("--------getAll-----");  
    List<TaskVO>  all = taskService.getAll();  
    return all;  
}

}

坑1:

首先再次强调Feign是通过http协议调用服务的,重点是要理解这句话: 如果FeignClient中的方法有@PostMapping注解,则微服务TaskApiController中对应方法的注解也应当保持一致为@PostMapping

若果不一致,则会报404的错误  。

调用失败后会触发它的熔断机制,如果@FeignClient中不写@FeignClient(fallback = TaskFeignClientDegraded.class),会直接报错

    11:00:35.686 [http-apr-8086-exec-8] DEBUG c.b.p.m.b.c.AbstractBaseController - Got an exception
com.netflix.hystrix.exception.HystrixRuntimeException: TaskFeignClient#getAll() failed and no fallback available.
    at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:819)
    at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:804)

坑2:

这个是最惨的了,自己写好的微服务没有运行起来,然后自己的客户端调用这个服务怎么也调用不成功还不知道问题在哪

当时自己微服务运行后,控制台如下

Process finished with exit code 0

我以前以为Process finished with exit code 1才是运行失败的意思 ,

所以只要出现 Process finished with exit code 就说明运行失败

服务成功启动的标志为

11:29:16.483 [restartedMain] INFO  c.b.p.ms.tsa.TsaServiceApplication - Started TsaServiceApplication in 37.132 seconds (JVM running for 39.983)。

坑3

报错:RequestParam.value() was empty on parameter 0

  如果在FeignClient中的方法有参数传递一般要加@RequestParam(“xxx”)注解

  错误写法:

@FeignClient(qualifier = "taskFeignClient", name = "service-tsa",fallback = TaskFeignClientDegraded.class)
public interface TaskFeignClient {
@PostMapping(value = "taskApiController/getAll")
List getAll(String name);
}

//或者
@FeignClient(qualifier = "taskFeignClient", name = "service-tsa",fallback = TaskFeignClientDegraded.class)
public interface TaskFeignClient {
@PostMapping(value = "taskApiController/getAll")
List getAll(@RequestParam String name);
}

  正确写法:

@PostMapping(value = "taskApiController/getAll")
List getAll(@RequestParam("name") String name);

  微服务那边可以不写这个注解

  参考 https://blog.csdn.net/jxm007love/article/details/80109974

  疑问:在 SpringMVC 和 Springboot 中都可以使用 @RequestParam 注解,不指定 value 的用法,为什么到了 Spring cloud 中的 Feign 这里就不行了呢?

这是因为和 Feign 的实现有关。Feign 的底层使用的是 httpclient,在低版本中会产生这个问题,听说高版本中已经对这个问题修复了。

  参考:
     Fiegn Client with Spring Boot: RequestParam.value() was empty on parameter 0
     Feign bug when use @RequestParam but not have value
     https://www.xttblog.com/  业余草

坑四:

FeignClient中post传递对象和consumes = "application/json",按照坑三的意思,应该这样写。

@FeignClient(qualifier = "taskFeignClient", name = "service-tsa",fallback = TaskFeignClientDegraded.class)
public interface TaskFeignClient {
@PostMapping(value = "taskApiController/getAll")
List getAll(@RequestParam("vo") TaskVO vo);

}

  很意外报错

    16:00:33.770 [http-apr-8086-exec-1] DEBUG c.b.p.a.s.PrimusCasAuthenticationFilter - proxyReceptorRequest = false
    16:00:33.770 [http-apr-8086-exec-1] DEBUG c.b.p.a.s.PrimusCasAuthenticationFilter - proxyTicketRequest = false
    16:00:33.770 [http-apr-8086-exec-1] DEBUG c.b.p.a.s.PrimusCasAuthenticationFilter - requiresAuthentication = false
    16:00:34.415 [hystrix-service-tsa-2] DEBUG c.b.p.m.b.f.PrimusSoaFeignErrorDecoder - error json:{
    "timestamp":1543564834395,
    "status":500,
    "error":"Internal Server Error",
    "exception":"org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException","message":"Failed to convert value of type 'java.lang.String' to required type 'com.model.tsa.vo.TaskVO';
    nested exception is java.lang.IllegalStateException:
    Cannot convert value of type 'java.lang.String' to required type 'com.model.tsa.vo.TaskVO':
    no matching editors or conversion strategy found","path":"/taskApiController/getAll"  }

  开着错误信息想了半天突然想明白了,Feign本质是通过http 请求的,http怎么能直接传递对象呢,一般都是把对象转换为json通过post请求传递的

  正确写法应当如下

@FeignClient(qualifier = "taskFeignClient", name = "service-tsa",fallback = TaskFeignClientDegraded.class)
public interface TaskFeignClient {
@PostMapping(value = "taskApiController/getAll",,consumes = "application/json")
List getAll(TaskVO vo);
}

  也可以这样写

@PostMapping(value = "taskApiController/getAll")
List getAll(@RequestBody TaskVO vo);

  此时不用,consumes = "application/json"

但是第一种写法最正确的    因为FeignClient是在我们本地直接调用的,根本不需要这个注解,Controller调用方法的时候就是直接将对象传给FeignClient,而FeignClient通过http调用服务时则需要将对象转换成json传递。

https://bushkarl.gitbooks.io/spring-cloud/content/spring_cloud_netflix/declarative_rest_client_feign.html

微服务这边如下

@Slf4j
@RestController
@RequestMapping("taskApiController")
public class TaskApiController{
@Autowired
private TaskService taskService;

@PostMapping("/getAll")  
public List<TaskVO> getAll(@RequestBody TaskVO vo) {  
    log.info("--------getAll-----");  
    List<TaskVO>  all = taskService.getAll();  
    return all;  
}  

}

  我第一次写这个的时候方法参数里面什么注解都没加,可以正常跑通,但是传过去的对象却为初始值,实际上那是因为对象根本就没传

如果用get方法传递对象呢?

  参考:

     https://blog.csdn.net/cuiyaoqiang/article/details/81215483

     https://blog.csdn.net/u014281502/article/details/72896182

     https://blog.csdn.net/neosmith/article/details/52449921

  当然还是推荐使用post请求传递对象的

传递对象的另一种方法和多参传递

来源:https://www.jianshu.com/p/7ce46c0ebe9d

          http://www.itmuch.com/spring-cloud-sum/feign-multiple-params/

1、GET请求多参数的URL

假设我们请求的URL包含多个参数,例如http://microservice-provider-user/get?id=1&username=张三 ,要怎么办呢?

我们知道Spring Cloud为Feign添加了Spring MVC的注解支持,那么我们不妨按照Spring MVC的写法尝试一下:

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public User get0(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":"/get"}

由异常可知,尽管指定了GET方法,Feign依然会发送POST请求。

正确写法如下:

(1) 方法一

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

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User get1(@RequestParam("id") Long id, @RequestParam("username") String username);

}

  这是最为直观的方式,URL有几个参数,Feign接口中的方法就有几个参数。使用@RequestParam注解指定请求的参数是什么。

(2) 方法二

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
@RequestMapping(value = "/get", method = RequestMethod.GET)
public User get2(@RequestParam Map map);

}

  多参数的URL也可以使用Map去构建

当目标URL参数非常多的时候,可使用这种方式简化Feign接口的编写。

POST请求包含多个参数

  下面我们来讨论如何使用Feign构造包含多个参数的POST请求。实际就是坑四,把参数封装成对象传递过去就可以了。

最后拓展一下

Feign的Encoder、Decoder和ErrorDecoder

  Feign将方法签名中方法参数对象序列化为请求参数放到HTTP请求中的过程,是由编码器(Encoder)完成的。同理,将HTTP响应数据反序列化为java对象是由解码器(Decoder)完成的。

默认情况下,Feign会将标有@RequestParam注解的参数转换成字符串添加到URL中,将没有注解的参数通过Jackson转换成json放到请求体中。

注意,如果在@RequetMapping中的method将请求方式指定为get,那么所有未标注解的参数将会被忽略,例如:

@RequestMapping(value = "/group/{groupId}", method = RequestMethod.GET)
void update(@PathVariable("groupId") Integer groupId, @RequestParam("groupName") String groupName, DataObject obj);

  此时因为声明的是GET请求没有请求体,所以obj参数就会被忽略。

在Spring Cloud环境下,Feign的Encoder*只会用来编码没有添加注解的参数*。如果你自定义了Encoder, 那么只有在编码obj参数时才会调用你的Encoder。对于Decoder, 默认会委托给SpringMVC中的MappingJackson2HttpMessageConverter类进行解码。只有当状态码不在200 ~ 300之间时ErrorDecoder才会被调用。ErrorDecoder的作用是可以根据HTTP响应信息返回一个异常,该异常可以在调用Feign接口的地方被捕获到。我们目前就通过ErrorDecoder来使Feign接口抛出业务异常以供调用者处理。
 

Feign的HTTP Client

  https://blog.csdn.net/neosmith/article/details/52449921
         Feign在默认情况下使用的是JDK原生的URLConnection发送HTTP请求,没有连接池,但是对每个地址会保持一个长连接,即利用HTTP的persistence connection 。我们可以用Apache的HTTP Client替换Feign原始的http client, 从而获取连接池、超时时间等与性能息息相关的控制能力。Spring Cloud从Brixtion.SR5版本开始支持这种替换,首先在项目中声明Apache HTTP Client和feign-httpclient依赖:


org.apache.httpcomponents httpclient
com.netflix.feign feign-httpclient ${feign-httpclient}

然后在application.properties中添加:

feign.httpclient.enabled=true

通过Feign, 我们能把HTTP远程调用对开发者完全透明,得到与调用本地方法一致的编码体验。这一点与阿里Dubbo中暴露远程服务的方式类似,区别在于Dubbo是基于私有二进制协议,而Feign本质上还是个HTTP客户端。如果是在用Spring Cloud Netflix搭建微服务,那么Feign无疑是最佳选择。

原文链接:

  https://blog.csdn.net/uotail/article/details/84673347

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章