服务拆分及远程调用
1 服务拆分注意事项
- 不同微服务,不要重复开发相同业务
- 微服务数据独立,不要访问其它微服务的数据库
- 微服务可以将自己的业务暴露为接口,供其它微服务调用

2 微服务远程调用
2.1 根据订单id查询订单功能
需求:根据订单id查询订单的同时,把订单所属的用户信息一起返回

2.2 远程调用方式分析

微服务远程调用-查询订单
步骤:
-
注册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); } /** * 创建RestTemplate并注入到Spring容器 * @return */ @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } } -
服务远程调用RestTemplate(修改order-service中的OrderService的queryOrderByld方法
@Service public class OrderService { @Autowired private OrderMapper orderMapper; @Autowired private RestTemplate restTemplate; public Order queryOrderById(Long orderId) { // 1.查询订单 Order order = orderMapper.findById(orderId); // 2.利用RestTemplate发起http请求,通过id查询用户信息 // 2.1.url路径 String url = "http://localhost:8081/user/"+order.getUserId(); // 2.2.发起http请求,实现远程调用 // 默认返回值是Json对象,可以指定特定的类反序列化为指定对象 User user = restTemplate.getForObject(url, User.class); // 3.封装user到Order order.setUser(user); // 4.返回 return order; } }
3 提供者和消费者
- 服务提供者:一次业务中,被其它微服务调用的服务。(提供接口给其它微服务)
- 服务消费者:一次业务中,调用其它微服务的服务。(调用其它微服务提供的接口)

一个服务既可以是服务提供者,也可以是服务消费者
本文探讨了微服务架构中的服务拆分原则,强调每个微服务应独立且避免重复业务,同时数据也应保持独立。在远程调用方面,通过一个例子展示了如何使用RestTemplate进行服务间的通信,以查询订单并获取关联的用户信息。此外,解释了服务提供者和服务消费者的概念,指出一个服务可能同时扮演这两个角色。
1720

被折叠的 条评论
为什么被折叠?



