微服务框架SpringCloud-2-服务拆分及远程调用-2.2服务远程调用

微服务框架 SpringCloud

2 服务拆分及远程调用

2.2 服务远程调用

2.2.1 根据订单id查询订单功能

需求:根据订单id查询订单的同时,把订单所属的用户信息一起返回

现在是不能做到的,

 可以看到现在user 是个 null 【所以没有达到需求】

现在的情况是下面的样子

 

 但是需求想要的是下面的样子

 即在查询订单的同时,把用户信息也返回

所以现在必须得修改订单模块的内容了

 这就要涉及到服务远程调用了

2.2.2 远程调用方式分析

 现在的user 服务对外暴露了一个get 请求接口

 现在在浏览器直接请求接口,就可以得到对应id 的user 信息

如果我的订单模块也可以像浏览器一样发起一个http 请求,

 这样用户模块也应该返回对应的用户信息

这样订单模块再对两部分信息进行整合

 即如何在Java 代码中发起http 请求

2.2.3 实现

① 注册RestTemplate

在order-service的OrderApplication中注册RestTemplate

package cn.itcast.order;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {

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

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

}

② 服务远程调用RestTemplate

修改order-service中的OrderService的queryOrderById方法

package cn.itcast.order.service;

import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @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;
    }
}

OK,重启服务

 进行测试

 妙啊,这样就都出来了【虽然实现的方式有点…】

试下另外的

 没问题没问题

2.2.4 实现

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

 

posted @ 2023-05-24 15:23  爵岚  阅读(25)  评论(0编辑  收藏  举报