Feign客户端的定义和注入使用及注意事项

叁歲伎倆 2022-12-22 08:44 263阅读 0赞

业务场景:
用户服务customer调用订单服务order。
解决问题:
Feign客户端的定义,Feign客户端的注入使用。

一、Feign客户端的定义及项目模块划分

order项目分模块,在order-dto中定义Feign客户端接口。
dto中同时定义入参Req和出参DTO,便于其他模块中的微服务最小化最精简引入依赖。
注意:接口参数中都添加上各自注解,否则会产生文末的异常。

  1. package com.szh.order.api;
  2. @FeignClient(value = OrderApi.SERVICE_NAME)
  3. public interface OrderApi {
  4. final String SERVICE_NAME = "order";
  5. @RequestMapping(path = "/order/save", method = RequestMethod.POST)
  6. ApiResponse<OrderBaseDTO> saveOrder(@RequestBody SaveOrderReq req);
  7. @RequestMapping(path = "/order/info", method = RequestMethod.GET)
  8. ApiResponse<List<OrderDTO>> getOrder(@RequestParam("customer_name") String customerName,
  9. @RequestParam("customer_phone") String customerPhone);
  10. }

order-web中的Controller实现自身服务的FeignApi接口。

  1. package com.szh.order.ctrl;
  2. @RestController
  3. public class OrderCtrl implements OrderApi {
  4. @Override
  5. public ApiResponse<OrderBaseDTO> saveOrder(@Validated @RequestBody SaveOrderReq req) {
  6. // TODO
  7. return ApiResponse.success(null);
  8. }
  9. @Override
  10. public ApiResponse<List<OrderDTO>> getOrder(@RequestParam("customer_name") String customerName,
  11. @RequestParam("customer_phone") String customerPhone) {
  12. // TODO
  13. return ApiResponse.success(null);
  14. }
  15. }

二、其他微服务注入Feign调用

customer引入order-dto的pom后注入。

  1. package com.szh.customer.service;
  2. import com.szh.order.api.OrderApi;
  3. @Service
  4. @Slf4j
  5. public class CustomerServiceImpl implements CustomerService {
  6. @Autowired
  7. private OrderApi orderApi;
  8. @Override
  9. public UserOrderDTO getMyOrder(String userName, String userPhone) {
  10. ApiResponse<List<OrderDTO>> resp = orderApi.getOrder(userName, userPhone);
  11. log.info("用户相关的订单信息: {}", JSON.toJSONString(resp));
  12. // TODO
  13. return null;
  14. }
  15. }

注意点1

Field orderApi in com.szh.customer.service.CustomerServiceImpl required a bean of type 'com.szh.order.api.OrderApi' that could not be found.
原因:
未扫描到引入的Feign客户端。
解决方法:
用户服务主类指定Feign扫描包需包含order-dto。

  1. @EnableFeignClients({ "com.szh.*.api"})

注意点2

java.lang.IllegalStateException: Method has too many Body parameters
原因:
多个接口参数下,未添加各自注解。

  1. package com.szh.order.api;
  2. @FeignClient(value = OrderApi.SERVICE_NAME)
  3. public interface OrderApi {
  4. final String SERVICE_NAME = "order";
  5. @RequestMapping(path = "/order/save", method = RequestMethod.POST)
  6. ApiResponse<OrderBaseDTO> saveOrder(SaveOrderReq req);
  7. @RequestMapping(path = "/order/info", method = RequestMethod.GET)
  8. ApiResponse<List<OrderDTO>> getOrder(String customerName, String customerPhone);
  9. }

解决方法:
Feign客户端接口参数都最好添加上各自注解,如@RequestParam、@RequestHeader、@PathVariable、@RequestBody等。

发表评论

表情:
评论列表 (有 0 条评论,263人围观)

还没有评论,来说两句吧...

相关阅读

    相关 定义方法注意事项

    定义方法时什么时候需要有返回值? 当我们需要获得该方法的结果在别的方法里面使用时需要给方法返回值。 定义方法什么时候需要参数? 当我们定义的这个方法能够在多处地方