spring-cloud 开发 - RestTemplate 远程调用 HTTP 接口

现在有这样一个场景,我们要实现一个订单服务和一个商品服务,两个服务程序部署在不同的服务器上,当我们获取订单信息时,订单信息中要包含有商品信息,所以订单服务要向商品服务发送请求获取商品信息,这个流程怎么实现呢?

订单服务和商品服务在两个不同的服务器上,所以订单服务要想获取商品信息就得发送 HTTP 请求给商品服务获取,这个 HTTP 请求的发送就得用到 RestTemplate

RestTemplate

RestTemplate 是 Spring Framework 中的一个类,用于发送 HTTP 请求到 RESTful Web 服务。它提供了多种方法来发送请求(GET、POST、PUT、DELETE 等),并将响应转换为 Java 对象。RestTemplate 简化了与 RESTful 服务的交互,使得发送 HTTP 请求和处理响应变得更为简单和直观。

解决流程

1.向 Spring 的 IoC 容器中注入 RestTemplate 对象

java 复制代码
@Configuration
public class BeanConfig {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

2.注入 RestTemplate 对象并发送 HTTP 请求到对应接口获取数据

java 复制代码
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    public OrderInfo selectOrderById(Integer orderId){
        OrderInfo orderInfo = orderMapper.selectOrderById(orderId);
        String url = "http://127.0.0.1:9090/product/info/"+orderInfo.getProductId();
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
}

上述代码最核心的是:

java 复制代码
String url = "http://127.0.0.1:9090/product/info/"+orderInfo.getProductId();
ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);

url 是商品服务器提供的获取商品信息的接口,restTemplate 对象调用 getForObject 表示向 url 对应的接口发送 HTTP 请求,将获取到的数据转换成 ProductInfo类型的对象并返回

此时我们就完成了在订单服务上发送 HTTP 请求给商品服务,获取商品信息。

相关推荐
不可能的是17 小时前
前端 SSE 流式请求三种实现方案全解析
前端·http
Jony_2 天前
高可用移动网络连接
网络协议
chilix3 天前
Linux 跨网段路由转发配置
网络协议
DianSan_ERP4 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅4 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19984 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
2501_946205524 天前
晶圆机器人双臂怎么选型?适配2-12寸晶圆的末端效应器有哪些?
服务器·网络·机器人
linux kernel4 天前
第七部分:高级IO
服务器·网络
数字护盾(和中)4 天前
BAS+ATT&CK:企业主动防御的黄金组合
服务器·网络·数据库
~远在太平洋~4 天前
Debian系统如何删除多余的kernel
linux·网络·debian