微服务远程调用 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();
    }
}
相关推荐
微三云 - 廖会灵 (私域系统开发)7 分钟前
电商系统API设计与开放平台建设:从内部调用到商业化API交付的架构演进
架构
AI应用苏大大36 分钟前
企业AI采购决策架构缺陷:服务商主导选型导致技术绑架与成本失控的优化方案
人工智能·架构
薛定猫AI1 小时前
【技术干货】目标驱动型编码智能体实战:用 Claude Opus 4.8 构建可验证的开发任务闭环
人工智能·架构
qq_454245031 小时前
GraphFoundation — 通用图基础框架
算法·架构
胡萝卜术10 小时前
深度重构:Agent Skills——从 Prompt 工程到能力工程
javascript·架构·github
踏月的造梦星球10 小时前
DMDPC 学习:架构、部署、运维与调优
运维·数据库·学习·架构
韩楚风11 小时前
【参天引擎】事务生命周期 / MVCC / Undo / ACID / 分布式事务 功能域整体解析
数据库·分布式·mysql·架构·cantian
通问AI11 小时前
Apple Intelligence 国行备案深度技术解析:阿里千问如何被集成到苹果端侧AI架构
人工智能·架构
明航咨询—张老师11 小时前
软考软件评测师技术深度剖析:2026年考试改革后的知识体系与备考架构
大数据·架构
一路向北North12 小时前
Spring Security OAuth2.0(23):分布式系统授权-转发明文给微服务
java·spring·微服务