服务拆分注意事项
1.不同微服务、不要重复开发相同业务。 2.微服务数据独立,不要访问其他微服务的数据库。 3.微服务将自己的业务暴露为接口,供其他微服务调用。
案例demo
服务拆分 根据单一职责可以划分为以下两个服务
远程调用
本例中 , 订单微服务 远程调用 用户服务,结果组合在一起。返回给前端。
如何完成远程调用? 订单发起Http 请求即可。
spring 提供的远程调用工具 【RestTemplate】
、
由于 SpringBootApplication 本身也是配置类 在
主类里将Bean 装配到容器也是可行的
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
/**
* 创建 RestTemplate 并 注入 spring 容器。
*
* @return {@link RestTemplate}
*/
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
service 修改
public Order queryOrderById(Long orderId) {
Order order = orderMapper.findById(orderId);
String url = "http://localhost:8081/user/" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
return order;
}
生产者和消费者
- 服务生产者 : 一次业务中,被其它微服务调用的服务(提供接口给其它微服务)。
- 服务消费者 : 一次业务中,调用其他微服务的服务(调用其他微服务提供的接口)。