一、引入 Feign 依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
二、添加 Feign 注解
在服务启动类添加注解,开启 Feign 功能:
@EnableFeignClients @MapperScan("cn.itcast.order.mapper") @SpringBootApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }
三、编写 Feign 客户端
@FeignClient("userService") public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
四、使用 Feign 客户端调用接口
@Autowired private UserClient userClient; public Order queryOrderById(Long orderId) { // 1.查询订单 Order order = orderMapper.findById(orderId); // 2.获取用户信息 User user = userClient.findById(order.getUserId()); // 3.将 User 封装到 Order 中 order.setUser(user); // 4.返回 return order; }
注:个人笔记,摘自黑马