Spring Boot 和 Spring Cloud Feign调用服务及传递参数踩坑记录

@FeignClient

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

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


/**
 * 文件服务
 *
 * @author ymf
 */
@FeignClient(contextId = "remoteMessageService", value = ServiceNameConstants.MESSAGE_SERVICE, fallbackFactory = RemoteMessageFallbackFactory.class)
public interface RemoteMessageService {

    String prefix = "/message";

    /**
     * 发送消息
     *
     * @return 结果
     */
    @PostMapping(value = prefix + "/send", consumes = MediaType.APPLICATION_JSON_VALUE)
    SysStatus send(BaseMessage baseMessage);

}

微服务端

@Slf4j
@RestController
@RequestMapping("/message")
public class TaskApiController{
 
    @Autowired
    private RemoteMessageService remoteMessageService ;
 
    @PostMapping("/send")
    public SysStatus  send(@RequestBody BaseMessage baseMessage) {
        SysStatus status = remoteMessageService.send(baseMessage);
        return status;
    }
}

坑1:

首先再次强调Feign是通过http协议调用服务的,重点是要理解这句话

如果FeignClient中的方法有@PostMapping注解则微服务TaskApiController中对应方法的注解也应当保持一致为@PostMapping如果不一致,则会报404的错误

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

坑2:RequestParam.value() was empty on parameter 0

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


@PostMapping(value = "/attach/detail", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
AttachDto findByFileDigest(String fileDigest);
}

错误写法2


@PostMapping(value = "/attach/detail", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
AttachDto findByFileDigest(@RequestParam String fileDigest);
}

正确写法

@PostMapping(value = "/attach/detail", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
AttachDto findByFileDigest(@RequestParam("fileDigest") String fileDigest);

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

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

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

坑3 FeignClient中post传递对象和consumes = “application/json”

按照坑2的意思,应该这样写



/**
 * 文件服务
 *
 * @author ymf
 */
@FeignClient(contextId = "remoteMessageService", value = ServiceNameConstants.MESSAGE_SERVICE, fallbackFactory = RemoteMessageFallbackFactory.class)
public interface RemoteMessageService {

    String prefix = "/message";

    /**
     * 发送消息
     *
     * @return 结果
     */
    @PostMapping(value = prefix + "/send")
    SysStatus send(@RequestParam("baseMessage") BaseMessage baseMessage);

}

很意外报错

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.BaseMessage'; 
nested exception is java.lang.IllegalStateException: 
Cannot convert value of type 'java.lang.String' to required type 'com.model.tsa.vo.BaseMessage':
no matching editors or conversion strategy found","path":"/message/send"  }

开着错误信息想了半天突然想明白了

Feign本质是通过http 请求的,http怎么能直接传递对象呢,一般都是把对象转换为json通过post请求传递的

正确写法应当如下

   String prefix = "/message";

    /**
     * 发送消息
     *
     * @return 结果
     */
     //APPLICATION_JSON_VALUE = "application/json";
    @PostMapping(value = prefix + "/send", consumes = MediaType.APPLICATION_JSON_VALUE)
    SysStatus send(BaseMessage baseMessage);

也可以这样写

   String prefix = "/message";

    /**
     * 发送消息
     *
     * @return 结果
     */
     //APPLICATION_JSON_VALUE = "application/json";
    @PostMapping(value = prefix + "/send")
    SysStatus send(@RequestBody BaseMessage baseMessage);

此时不用,consumes = “application/json”

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

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

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<String, Object> map);
}

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

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

2、POST请求包含多个参数

下面我们来讨论如何使用Feign构造包含多个参数的POST请求。

实际就是坑四,把参数封装成对象传递过去就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值