好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringCloud:feign对象传参和普通传参及遇到的坑解决

feign对象传参和普通传参及遇到的坑

对象传参

使用@RequestBody来指定传参对象

?

1

2

@RequestMapping (value = "/v2/matterCode/genCode" , method = RequestMethod.POST)

    ResultResponse<String> getCode( @RequestBody MatterCodeBO matterCodeBO);

注意:@RequestBody在一个方法内有且只有一个,不能同时存在两个!

普通传参

普通传参使用@RequestParam来指定参数

?

1

2

@RequestMapping (value = "taskApiController/getAll" , method = RequestMethod.POST)

List<TaskVO> getAll( @RequestParam ( "name" ) String name);

注意:@RequestParam必须指定参数名("name"),否则报错:RequestParam.value() was empty on parameter 0

遇到的坑-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

报错信息:

feign.FeignException:status 400 reading xxx#xxxx(String); content:

原因: 因为feign的那个方法使用的@ReqestParam注解,这个接收的参数长度过长造成的,这也是feign就算使用post方法,参数也会放在请求地址后面,而不是放在请求体里面。

解决办法: 将参数封装成对象,使用@RequestBody标明参数

feign传递复杂参数对象需要注意的地方

传递复杂参数对象需要用Post

另外需要注意,Feign不支持使用GetMapping 和PostMapping

?

1

@RequestMapping (value= "user/save" ,method=RequestMethod.POST)

在传递的过程中

复杂对象使用@RequestBody进行注解,同时接收端也需要使用@RequestBody这个注解。 

我遇一个坑:

消费端使用了@RequestBody而服务端没有接收@RequestBody,这时参数会接收不完整。

?

1

2

3

4

5

6

7

8

9

//消费端

     @RequestMapping (value= "user/save" ,method=RequestMethod.POST)

     public User save( @RequestBody User user);

//服务端

@PostMapping ( "save" )

     public User save( @RequestBody User user) {

         System.out.println(user);

         return UserService.save(user);

     }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/uotail/article/details/84673347

查看更多关于SpringCloud:feign对象传参和普通传参及遇到的坑解决的详细内容...

  阅读:34次