第一步:引入依赖
<!--引入feign的客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
第二步:在服务的启动类添加注解开启Feign的功能
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
第三步:声明一个接口,编写Feign客户端
@org.springframework.cloud.openfeign.FeignClient("userservice")
public interface FeignClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
主要是基于SpringMVC的注解来声明远程调用的信息
服务名称:userservice
请求方式:GET
请求路径:/user/{id}
请求参数:Long id
返回值类型:User
第四步:用Feign客户端代替RestTemplate
@Autowired
private FeignClient feignClient;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
//2.获取用户id
Long userId = order.getUserId();
User byId = feignClient.findById(userId);
order.setUser(byId);
// 4.返回
return order;
}