微服务远程调用 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();
    }
}
相关推荐
what丶k42 分钟前
深入理解Redis哨兵(Sentinel)原理:高可用架构的核心守护者
redis·缓存·架构
数据与后端架构提升之路1 小时前
论微服务架构在电商交易系统中的设计与应用
微服务·架构·软考
cjqbg3 小时前
灵芽API:企业级大模型API聚合网关架构解析与成本效益对比
人工智能·架构·aigc·ai编程
小雨青年3 小时前
【鸿蒙原生开发会议随记 Pro】 数据存储架构 RelationalStore 在复杂资产管理中的应用
华为·架构·harmonyos
敲敲了个代码3 小时前
多标签页强提醒不重复打扰:从“弹框轰炸”到“共享待处理队列”的实战
java·前端·javascript·面试·架构
Henry Zhu1234 小时前
Qt Model/View架构详解(四):高级特性
开发语言·qt·架构
十月南城4 小时前
压测方法论——目标、场景、指标与容量评估的闭环
运维·web安全·ci/cd·微服务·云计算
Henry Zhu1235 小时前
Qt Model/View架构详解(五):综合实战项目
开发语言·qt·架构
梵高的代码色盘6 小时前
互联网大厂Java求职面试实录与技术深度解析
java·spring·缓存·微服务·面试·互联网大厂·技术深度
马士兵教育6 小时前
AI大模型通用智能体项目从原理到落地:Agent Skills 的核心逻辑与中间件 + 动态工具实践方案+架构项目实战!
人工智能·中间件·架构