携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第21天,点击查看活动详情
⭐️前面的话⭐️
✉️坚持和努力一定能换来诗与远方!
💭推荐书籍:📚《王道408》,📚《深入理解 Java 虚拟机-周志明》,📚《Java 核心技术卷》
💬算法刷题:✅力扣🌐牛客网
🎈Github
🎈码云Gitee
二、微服务拆分案例
服务提供者:一次业务中,被其它微服务调用的服务。(提供接口给其它微服务)
服务消费者:一次业务中,调用其它微服务的服务。(调用其它微服务提供的接口)
# 服务A调用服务B,服务B调用服务C,那么服务B是什么角色?
一个服务既可以是提供者,也可以是消费者。
所谓服务拆分
# 父工程
定义版本
# 注意事项📢
单一职责:不同微服务,不要重复开发相同业务
数据独立:不要访问其它微服务的数据库
面向服务:将自己的业务暴露为接口,供其它微服务调用
案例cloud-demo(微服务远程调用--查询订单)
1)注册RestTemplate
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
/**
* 创建RestTemplate并注入Spring容器
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
2)服务远程调用RestTemplate(url中使用硬编码的方式)
修改order-service中 OrderService 的queryOrderById方法:
基于RestTemplate发起的http请求实现远程调用。
http请求做远程调用是与语言无关的调用,只要知道对方的ip、端口、接口路径、请求参数即可。
@Service
public class OrderService {
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
// 2.利用RestTemplate发起http请求,查询用户
// 2.1.url路径
String url = "http://localhost:8081/user/" + order.getUserId();
// 2.2.发送http请求,实现远程调用
User user = restTemplate.getForObject(url, User.class);
// 3.封装user到Order
order.setUser(user);
// 4.返回
return order;
}
}
服务提供者与服务消费者的概念
服务提供者:一次业务中,被其它微服务调用的服务。(提供接口给其它微服务)
服务消费者:一次业务中,调用其它微服务的服务。(调用其它微服务提供的接口)
# 服务A调用服务B,服务B调用服务C,那么服务B是什么角色?
一个服务既可以是提供者,也可以是消费者。