微服务远程调用 RestTemplate

Spring给我们提供了一个RestTemplate的API,可以方便的实现Http请求的发送。

同步客户端执行HTTP请求,在底层HTTP客户端库(如JDK HttpURLConnection、Apache HttpComponents等)上公开一个简单的模板方法API。RestTemplate通过HTTP方法为常见场景提供了模板,此外还提供了支持不太常见情况的通用交换和执行方法。 RestTemplate通常用作共享组件。然而,它的配置不支持并发修改,因此它的配置通常是在启动时准备的。如果需要,您可以在启动时创建多个不同配置的RestTemplate实例。如果这些实例需要共享HTTP客户端资源,它们可以使用相同的底层ClientHttpRequestFactory。 注意:从5.0开始,这个类处于维护模式,只有对更改和错误的小请求才会被接受。请考虑使用org.springframework.web.react .client. webclient,它有更现代的API,支持同步、异步和流场景。

1. 添加依赖

首先,确保你的Spring Boot项目中已经添加了spring-web依赖,因为RestTemplate类包含在这个模块中。

XML 复制代码
<!-- 在pom.xml中添加依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.创建配置类

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

3. 使用RestTemplate

在你的服务类中,你可以通过注入RestTemplate Bean来使用它。

java 复制代码
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private final RestTemplate restTemplate;

    // 通过构造器注入 RestTemplate
    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchDataFromApi(String url) {
        // 使用 RestTemplate 发送 GET 请求
        ResponseEntity<String> response = restTemplate.exchange(
                url,//请求路径
                org.springframework.http.HttpMethod.GET,//请求方式
                null,//请求实体
                String.class  // 指定响应体类型为 String
        );

    if(!response.getStatusCode().is2xxSuccessful()){
        // 查询失败,直接结束
        return;
    }

        // 返回响应体
        return response.getBody();
    }
}
相关推荐
500841 分钟前
Conv + BN + ReLU 融合:省掉两次显存读写
flutter·架构·开源·wpf·音视频
计算机魔术师2 小时前
【AI面试八股文 Vol.3.4:训练微调部署选型】从预训练到量化部署:LLM 工程落地如何做模型选择
人工智能·后端·面试·架构·moe·vol.3.3·vol.3.4
therese_100863 小时前
客户端设计(下):场景流派与实战设计方式
架构·安卓·鸿蒙
魏杨杨3 小时前
被流量逼出来的架构:从一台服务器到云原生的 17 次蜕变 —— 集群、缓存、MQ、微服务、Docker、K8S 的前世今生
微服务·k8s·负载均衡·ddd·分部署
乌恩大侠4 小时前
基站正在成为 AI 计算节点:NVIDIA Aerial 推动 RAN 架构重构
人工智能·重构·架构
Waay4 小时前
图文详解|K8s Pod内部结构
docker·云原生·kubernetes
码点滴4 小时前
CRI-O选型与容器运行时标准
开发语言·人工智能·架构·kubernetes·cri-o
openFuyao5 小时前
以开源之力,突破多样化算力困局——openFuyao开源一周年背后的故事
人工智能·云原生·开源·openfuyao·多样化算力·集群软件
JiaWen技术圈6 小时前
IaC 双引擎:Terraform + Ansible 完整最佳实践
云原生·ansible·terraform
Joy T6 小时前
【Web3】跨链 NFT 工程化实战:多环境配置与自动化状态查询机制
架构·web3·区块链·智能合约·hardhat·hardhat 3.x·跨链测试