SpringCloud开发实战(二):通过RestTemplate实现远程调用

目录
SpringCloud开发实战(一):搭建SpringCloud框架

RestTemplate介绍

RestTemplate 是 Spring 框架中的一个类,它用于促进 HTTP 请求的发送和接收,并且简化了与 RESTful 服务的交互。RestTemplate 提供了许多便利的方法来执行诸如 GET、POST、PUT 和 DELETE 这样的 HTTP 操作。它支持多种数据类型的消息转换,比如 JSON 和 XML,并且可以方便地与 Spring 的 HttpMessageConverters 配合使用来处理请求和响应体。

一、前言

在order-service服务中,有一个根据id查询订单的接口:
在这里插入图片描述
根据id查询订单,返回值是Order对象,如图:
在这里插入图片描述
这里的user是空的

而在user-service中有一个根据id查询用户的接口:
在这里插入图片描述
那如果我们现在要给这个User赋值,就是在查询订单的同时,根据订单中包含的userId查询出用户信息,一起返回。我们需要在order-service中 向user-service发起一个http的请求,调用http://localhost:8081/user/{userId}这个接口。

大概的步骤是这样的:

  • 注册一个RestTemplate的实例到Spring容器
  • 修改order-service服务中的OrderService类中的queryOrderById方法,根据Order对象中的userId查询User
  • 将查询的User填充到Order对象,一起返回

二、注册RestTemplate

首先,我们在order-service服务中的OrderApplication启动类中,注册RestTemplate实例:
在这里插入图片描述

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("org.demo.mapper")
@SpringBootApplication
public class OrderApplication {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}

三、实现远程调用

我们要在OrderService中注入RestTemplate ,然后再修改OrderService类中的queryOrderById方法,修改分成四步。具体看下面代码

import org.demo.entity.Order;
import org.demo.entity.User;
import org.demo.mapper.OrderMapper;
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 queryById(Long id) {
        //1.查询订单
        Order order = orderMapper.findById(id);

        //2.远程查询User
        //2.1 设置url地址
        String url = "http://localhost:8082/user/" + order.getUserId();
        //2.2发起调用
        User user = restTemplate.getForObject(url,User.class);
        //3.存入user对象中
        order.setUser(user);
        //返回
        return order;
    }
}

四、测试

最后我们来启动一下OrderService和UserService,测试User是否已经注入。同样是请求http://localhost:8081/order/101 地址,发现User已经成功注入了。
在这里插入图片描述
至此,我们成功通过RestTemplate实现远程调用,如果文章有任何错误,还请大家指出。不胜感激!!!

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天吃八顿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值