微服务远程调用 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();
    }
}
相关推荐
海宇大数据1 小时前
零信任架构实战:基于海宇全能小微企业报告构建自动化持牌网络小贷小微商户极速助业贷秒级全维风险决策网关
网络·人工智能·架构·自动化
云-缩影3 小时前
拆解函数计算 Serverless GPU 部署 AI 模型:Flux 生图和语音复刻怎么跑的
人工智能·云原生·serverless
Nablai6 小时前
LX系列多国语言能力技术解析:ESP32双栈架构下的语种策略设计
人工智能·架构
阿俊-全栈开发7 小时前
LikeShop 多商户 Java 版商城微服务模块拆分与部署架构演进实践
java·微服务·架构·likeshop开源商城·多商户源码
螺蛳粉 螺蛳粉7 小时前
第 02 篇:镜像分层与 containerd 2.x 实战:SystemdCgroup 与 pause 镜像配置踩坑(底座认知 02)
docker·云原生·容器·kubernetes·etcd·containerd·kube-apiserver
frjc7 小时前
分布式服务拆分实战指南:从底层逻辑到面试话术
微服务·面试·职场和发展
X54先生(人文科技)8 小时前
百度智能对 X54 先生学科底色评估
人工智能·深度学习·百度·架构
HelloWorld0018 小时前
拒绝被大模型算力绑架!基于语义复杂度与意图分流打造多模型混合动态路由网关(全套架构+实战)
架构
电子科技圈9 小时前
芯科科技2026年Tech Talks技术系列讲座再增添全新主题共探无线SoC架构演进与安全合规
科技·嵌入式硬件·mcu·物联网·安全·架构·iot
技术党9 小时前
大模型训练平台推荐问答:九章云极的DCU计费、全栈Serverless和Token交付分别适合谁
云原生·serverless