Feign 服务间请求方式以及参数总结

2,083 阅读2分钟

微服务架构的项目,在用Feign来进行服务间的调用。在互调的过程中,难免出现问题,根据错误总结了一下,主要是请求方式的错误和接参数的错误造成的。 以下通过分为三种情况说明,无参数,单参数,多参数,复杂对象。 有个建议就是为了保证不必要的麻烦,在写feign接口的时候,与我们的映射方法保持绝对一致,同时请求方式,请求参数注解也都不偷懒的写上,如果遵循这种规范,可以避开90%的调用错误。

A 无参情况  (被调用方接口内部不接收参数)
    1、Get 请求
    @PostMapping(value = "接口地址",method = RequestMethod.GET)
    public void noArgsGetDemo();
	
    2、Post 请求
    @RequestMapping(value = "接口地址",method = RequestMethod.POST)
    public void noArgsPostDemo();   
   /* 下面这种Post方式不建议(直接使用 @PostMapping) */
    @PostMapping(value = "接口地址")
    public void noArgsPostDemo();
    
B 单个参数 (被调用方接口中只有一个形式参数,杂对象Feign有可能存在无法解析对象的情况,可以通过字符串作为形式参数)
   1、Get  请求    /*get请求方式接参,只能使用RequestParam注解*/
    @RequestMapping(value = "接口地址",method = RequestMethod.GET)
    public void singleArgGetDemo(@RequestParam String name);
   
   2、Post 请求 
    @RequestMapping(value = "接口地址",method = RequestMethod.POST)
    public void singleArgPostDemo(@RequestParam String name); 
    
C 多个参数
  1、Get 请求 
    @RequestMapping(value = "接口地址",method = RequestMethod.GET)
    public void moreArgGetDemo(@RequestParam String name,@RequestParam String sex);
  
  2、Post 请求    /*多个参数只能有一个是requestBody方式,其他应该使用requestParam方式*/
    @RequestMapping(value = "接口地址",method = RequestMethod.POST)
    public void moreArgPostDemo(@RequestBody String name,@RequestParam String sex);
      
    @RequestMapping(value = "接口地址",method = RequestMethod.POST)
    public void moreArgPostDemo(@RequestParam String name,@RequestParam String sex);  
    
D 复杂对象转换成字符串   比如传list  set  可以先包装在一个对象或者先转成字符串
1、转成字符串
   List<ExtAccountImpl> list = reqData.getAsList("params", ExtAccountImpl.class);
   String params = JSONObject.toJSONString(list);
2、 被调用方 接口
	@RequestMapping(value = "接口地址", method = RequestMethod.POST)
	RspData complexArgDemo (@RequestParam("params") String params);
3、调用方内部转换成对象
   List<ExtAccountImpl> list = JSONObject.parseArray(params, ExtAccountImpl.class);

 复杂对象包装成对象   在掉用的过程中需要传递集合
@RequestMapping(value = "/needHealthAudit", method = RequestMethod.POST)
void complexArgDemo(@RequestBody NotificationHorsemanDataGet notificationHorsemanDataGet);

public class NotificationHorsemanDataGet {
    public List<Integer> sendHorsemanIds;
    public List<Integer> getSendHorsemanIds() {
        return sendHorsemanIds;
    }
    public void setSendHorsemanIds(List<Integer> sendHorsemanIds) {
        this.sendHorsemanIds = sendHorsemanIds;
    }
} 

注意 : 在使用 @RequestBody的接口实现类 Controller 中记得也需要使用 @RequestBody接收参数

       鲜花再美,也要落地
       方案再好,也要实现
       我们不是产品,不玩手机壳跟随主题改变颜色

在此感谢大佬以及队友的帮助,在去年的工作中得到了成长,小生不才,如有不当之处,望各位大佬指点一二!