微服务—远程调用(RestTemplate)

怼烎@ 2023-10-14 21:33 125阅读 0赞

在微服务的所有框架中,SpringCloud脱颖而出,它是目前国内使用的最广泛的微服务框架 (官网地址),它集成了各种微服务功能组件,并基于SpringBoot实现了这些组件的自动装配,从而提供了良好的开箱即用的体验

d20df8dc2a8d4f42bc7c872c39da4674.png

服务拆分

服务拆分注意事项:

  • 单一职责:不同的微服务,不要重复开发相同的业务
  • 数据独立:不要访问其他微服务的数据库
  • 面向服务:将自己的业务暴露为接口,供其他微服务调用

128eea9dc3fc4254864e34659fdf742f.png

分别的在自己的模块中查询到自己所需要的信息,但是两个服务之间没有任何的联系,我们怎么样才能实现远程调用功能将我们所需要的信息做一个整合返回给我们客户端呢?

假如服务A调用服务B,以后用A、B简称服务

一般有两种方式:

  • RestTemplate

1.在服务A的启动层中注册RestTemplate

  1. @MapperScan("***")
  2. @SpringBootApplication
  3. public class OrderApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(OrderApplication.class, args);
  6. }
  7. /**
  8. * 创建RestTemplate并注入Spring容器
  9. */
  10. @Bean
  11. public RestTemplate restTemplate() {
  12. return new RestTemplate();
  13. }

2.在A服务的service层远程调用RestTemplate

  1. @Autowired //进行依赖注入
  2. private RestTemplate restTemplate;
  3. public Order queryOrderById(Long orderId) {
  4. // 1.查询订单
  5. Order order = orderMapper.findById(orderId);
  6. // 2.利用RestTemplate发起http请求,查询用户
  7. // 2.1.url路径 服务B请求的URL路径
  8. String url = "http://http://127.0.0.1:8080/user/" + order.getUserId();
  9. // 2.2.发送http请求,实现远程调用
  10. User user = restTemplate.getForObject(url, User.class);
  11. // 3.封装user到Order
  12. order.setUser(user);
  13. // 4.返回
  14. return order;
  15. }

微服务调用方式:RestTemplate请求远程调用是与语言无关性的调用,只要知道对方的ip、端口、接口路径、请求参数即可

  • Feign客户端(后面会细讲)

服务调用的关系

  • 服务提供者:暴露接口给其他微服务调用
  • 服务消费者:调用其他微服务提供的接口
  • 提供者与消费者其实是相对的
  • 一个服务可以同时是服务提供者和服务消费者

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读