这篇文章主要介绍了SpringCloud Feign参数问题及解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

站在用户的角度思考问题,与客户深入沟通,找到集安网站设计与集安网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站建设、网站制作、企业官网、英文网站、手机端网站、网站推广、国际域名空间、虚拟主机、企业邮箱。业务覆盖集安地区。
今天遇到使用Feign调用微服务,传递参数时遇到几个问题
1.无参数
以GET方式请求
服务提供者
@RequestMapping("/hello")
public String Hello(){
return "hello,provider";
}服务消费者
@GetMapping("/hello")
String hello();2.单个参数
(1)GET——@PathVariable
服务提供者
@GetMapping("/test/{name}")
public String test(@PathVariable String name){
return "hello,"+name;
}服务消费者
@GetMapping("/test/{name}")
String test(@PathVariable("name") String name);(2)GET——@RequestParam
服务提供者
@RequestMapping("/test")
public String test(String name){return "hello,"+name;
}服务消费者
@RequestMapping("/test")
String test(@RequestParam String name);会遇到报错
RequestParam.value() was empty on parameter 0
解决方法:
加上注解的描述,修改为
@RequestMapping("/test")
String test(@RequestParam("name") String name);(3)POST
@RequestBody
不需要注解的描述
@RequestMapping("/test")
String test(@RequestBody String name);注:
2.Feign多参数的问题
(1)GET——@PathVariable
服务提供者
@GetMapping("/test/{name}/{xyz}")
public String test(@PathVariable String name,@PathVariable String xyz){
return "hello,"+name+","+xyz;
}
服务消费者
@GetMapping("/test/{name}/{xyz}")
String test(@PathVariable("name") String name,@PathVariable("xyz") String xyz);(1)GET——@RequestParam
服务提供者
@RequestMapping("/test")
public String test(String name,Integer type){
if(type==1){
return "hello,"+name;
}else{
return "hello,provider-"+name;
}
}服务消费者
@RequestMapping("/test")
String test(String name, Integer type);会遇到报错Method has too many Body parameters
说明:
如果服务消费者传过来参数时,全都用的是@RequestParam的话,那么服务提供者的Controller中对应参数前可以写@RequestParam,也可以不写
服务消费者feign调用时,在所有参数前加上@RequestParam注解
正确的写法
@RequestMapping("/test")
String test(@RequestParam("name") String name, @RequestParam("type") Integer type);(2)POST
如果接收方不变
服务消费者
@RequestMapping("/test")
String test(@RequestBody String name, @RequestBody Integer type);会遇到报错Method has too many Body parameters
服务消费者为
@RequestMapping("/test")
String test(@RequestBody String name, @RequestParam("type") Integer type);name的值会为null
说明:
如果服务消费者传过来参数,有@RequestBody的话,那么服务提供者的Controller中对应参数前必须要写@RequestBody
正确的写法
服务提供者
@RequestMapping("/test")
public String test(@RequestBody String name, Integer type){
if(type==1){
return "hello,"+name;
}else{
return "hello,provider-"+name;
}
}服务消费者正确的写法
@RequestMapping("/test")
String test(@RequestBody String name, @RequestParam("type") Integer type);可以接收到参数
总结:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。