服务拆分原则
微服务拆分时的几个原则:
以 spring-cloud-demo 为例,其结构如下:
spring-cloud-demo├── order-service└── user-service
spring-cloud-demo:父工程,管理依赖
- order-service:订单微服务,负责订单相关业务
- user-service:用户微服务,负责用户相关业务
要求:
- 订单微服务和用户微服务都必须有各自的数据库,相互独立
- 订单服务和用户服务都对外暴露 Restful 的接口
- 订单服务如果需要查询用户信息,只能调用用户服务的 Restful 接口,不能查询用户数据库
初始项目代码:链接
实现远程调用案例
案例需求
修改 order-service 中的根据 id 查询订单业务,要求在查询订单的同时,根据订单中包含的 userId 查询出用户信息,一起返回。
因此,我们需要在 order-service 中向 user-service 发起一个 http 的请求,调用 http://localhost:8081/user/{userId} 这个接口。
大概的步骤是这样的:
- 注册一个 RestTemplate 的实例到 Spring 容器
- 修改 order-service 服务中的 OrderService 类中的 queryOrderById 方法,根据 Order 对象中的 userId 查询 User
- 将查询的 User 填充到 Order 对象,一起返回
注册 RestTemplate
首先,我们在 order-service 服务中的 OrderApplication 启动类中,注册 RestTemplate 实例:
package cn.itcast.order;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.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();
}
}
实现远程调用
修改 order-service 服务中的 cn.itcast.order.service 包下的 OrderService 类中的 queryOrderById 方法:
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
// 2. 利用 RestTemplate 发起 http 请求,查询用户
String url = "http://localhost:8081/user/" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
// 3. 封装 user 到 Order
order.setUser(user);
// 4.返回
return order;
}
代码:链接
提供者与消费者
在服务调用关系中,会有两个不同的角色:
- 服务提供者:一次业务中,被其它微服务调用的服务。(提供接口给其它微服务)
- 服务消费者:一次业务中,调用其它微服务的服务。(调用其它微服务提供的接口)
但是,服务提供者与服务消费者的角色并不是绝对的,而是相对于业务而言。如果服务 A 调用了服务 B,而服务 B 又调用了服务 C,服务 B 的角色是什么?
- 对于 A 调用 B 的业务而言:A 是服务消费者,B 是服务提供者
- 对于 B 调用 C 的业务而言:B 是服务消费者,C 是服务提供者
因此,服务 B 既可以是服务提供者,也可以是服务消费者。
