前言
整个spring cloud学习系列文章主要用于记录B站黑马程序员spring could课程,所用资料可以去相关视频评论区领取。`
一、导入服务拆分demo
二、案例:根据订单id查询订单功能
需求:根据订单id查询订单的同时,把订单所属的用户信息一起返回
1.远程调用分析
由于订单模块和用户模块是不同的模块,如何实现跨模块间的调用?
- 注册RestTemplate
在order-service的OrderApplication中注册RestTemplate
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){ // 注册
return new RestTemplate();
}
}
- 服务远程调用RestTemplate
修改order-service中的OrderService的queryOrderById方法
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
// 2、查询用户
String url = "http://localhost:8081/user/" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
// 3、封装User信息
order.setUser(user);
// 4.返回
return order;
}
总结
-
微服务调用方式
1)基于RestTemplate发起的http请求实现远程调用
2)http请求做远程调用是与语言无关的调用,只要知道对方的ip、端口、接口路径、请求参数即可 -
提供者与消费者
提供者:一次业务中,被其他微服务调用的服务。(提供接口给其他微服务)
消费者:一次业务中,调用其他微服务的服务。(调用其他的微服务提供的接口)
在不同的场景中,同一个模块扮演不同的角色。