一、Fegin的使用步骤如下
1.引入依赖
我们在order-service服务的pom文件中引入feign的依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2.添加注解
在order-service的启动类添加注解(@EnableFeignClients)开启Feign的功能:
3.编写Feign的客户端
在order-service中新建一个接口,内容如下:
import cn.itcast.order.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient("userservice") public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
这个客户端主要是基于SpringMVC的注解来声明远程调用的信息,比如:
-
服务名称:userservice
-
请求方式:GET
-
请求路径:/user/{id}
-
请求参数:Long id
-
返回值类型:User
这样,Feign就可以帮助我们发送http请求
4.测试
修改order-service中的OrderService类中的queryOrderById方法
@Autowired private UserClient userClient; public Order queryOrderById(Long orderId) { // 1.查询订单 Order order = orderMapper.findById(orderId); User user = userClient.findById(order.getUserId()); order.setUser(user); // 4.返回 return order; }