(1) 方法一
1 2 3 4 5 | @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) 方法二
1 2 3 4 5 | @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接口的编写。
下面我们来讨论如何使用Feign构造包含多个参数的POST请求。举个例子,假设我们的用户微服务的Controller是这样编写的:
1 2 3 4 5 6 7 | @RestController public class UserController { @PostMapping ( "/post" ) public User post( @RequestBody User user) { ... } } |
我们的Feign接口要如何编写呢?答案非常简单,示例:
1 2 3 4 5 | @FeignClient (name = "microservice-provider-user" ) public interface UserFeignClient { @RequestMapping (value = "/post" , method = RequestMethod.POST) public User post( @RequestBody User user); } |
feign接口调用其他微服务中参数是集合对象(List<Java对象>)且请求方式是PUT或者POST方式的解决
首先,如果传输的是集合对象,一般的不是PUT或者POST请求都是可以用@RequestParam("…")的形式写在接口的新参中,比如
1 2 3 4 5 | @GetMapping ( "/find/sec/consume/product/category" ) public ResponseEntity<List<SecConsumeProductCategoryVO>> getSecConsumeProductCategory( @RequestParam ( "sellerIds" ) List<Long> sellerIds){ List<SecConsumeProductCategoryVO> secConsumeProductCategories = secConsumeProductBaseBusinessService.getSecConsumeProductCategory(sellerIds); return ResponseEntity.ok(secConsumeProductCategories); } |
而对于feign调用且参数是集合对象的情况, 在feign客户端,则可以使用如下方式,请求路劲的注解就不能直接使用@PutMapping或者@PostMapping了,而必须使用@RequestMapping,形参仍然使用注解@RequestBody
1 2 | @RequestMapping (value = "/cancel/daily/appointment" ,method = RequestMethod.PUT) public Void updateBatchDailyAppointment( @RequestBody List<PdProductDailyAppointmentDTO> cancelAppointmentDTOS /*String cancelAppointmentStr*/ ); |
而对于被调用方,则可以这样写
1 2 3 4 5 | @RequestMapping (value = "/cancel/daily/appointment" ,method = RequestMethod.PUT) public ResponseEntity<Void> updateBatchDailyAppointment( @RequestBody List<PdProductDailyAppointmentDTO> cancelAppointmentDTOS /*String cancelAppointmentStr*/ ){ pdProductDailyAppointmentBusinessService.updateBatchDailyAppointment(cancelAppointmentDTOS); return ResponseEntity.status(HttpStatus.CREATED).build(); } |
这样,就可以解决feign调用传输的是集合对象的问题啦
以上为个人经验,希望能给大家一个参考,也希望大家多多支持源码搜藏网。
热门源码