微服务—远程调用(RestTemplate)

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

 服务拆分

服务拆分注意事项:

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

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

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

一般有两种方式:

  • RestTemplate

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

@MapperScan("***")
@SpringBootApplication
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    /**
     * 创建RestTemplate并注入Spring容器
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

    @Autowired  //进行依赖注入
    private RestTemplate restTemplate;

    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.利用RestTemplate发起http请求,查询用户
        // 2.1.url路径  服务B请求的URL路径
        String url = "http://http://127.0.0.1:8080/user/" + order.getUserId();
        // 2.2.发送http请求,实现远程调用
        User user = restTemplate.getForObject(url, User.class);
        // 3.封装user到Order
        order.setUser(user);
        // 4.返回
        return order;
    }

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

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

服务调用的关系

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

猜你喜欢

转载自blog.csdn.net/dfdbb6b/article/details/132333955