spring cloud学习3

前言

整个spring cloud学习系列文章主要用于记录B站黑马程序员spring could课程,所用资料可以去相关视频评论区领取。`

一、导入服务拆分demo

在这里插入图片描述

二、案例:根据订单id查询订单功能

需求:根据订单id查询订单的同时,把订单所属的用户信息一起返回
在这里插入图片描述

1.远程调用分析

在这里插入图片描述
由于订单模块和用户模块是不同的模块,如何实现跨模块间的调用?

  1. 注册RestTemplate
    在order-service的OrderApplication中注册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();
    }
}
  1. 服务远程调用RestTemplate
    修改order-service中的OrderService的queryOrderById方法
 @Autowired
    private RestTemplate restTemplate;
    
    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2、查询用户 
        String url = "http://localhost:8081/user/" + order.getUserId();
        User user = restTemplate.getForObject(url, User.class);
        // 3、封装User信息 
        order.setUser(user);
        // 4.返回
        return order;
    }

总结

  1. 微服务调用方式
    1)基于RestTemplate发起的http请求实现远程调用
    2)http请求做远程调用是与语言无关的调用,只要知道对方的ip、端口、接口路径、请求参数即可

  2. 提供者与消费者
    提供者:一次业务中,被其他微服务调用的服务。(提供接口给其他微服务)
    消费者:一次业务中,调用其他微服务的服务。(调用其他的微服务提供的接口)
    在不同的场景中,同一个模块扮演不同的角色。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值