Spring Boot 中的HTTP请求方式详解:优缺点与代码示例

在Spring Boot中,有多种方式可以发起HTTP请求。主要的工具包括RestTemplateWebClient和增强的AsyncRestTemplate。本文将详细介绍每种请求方式及其优缺点,并给出代码示例。

1. RestTemplate

RestTemplate 是 Spring 提供的一个用于同步 HTTP 请求的客户端。它支持多种HTTP方法,例如GET、POST、PUT、DELETE等。

优点
  • 简单易用,适合处理同步请求。
  • 功能强大,支持多种HTTP方法和数据格式。
缺点
  • 是阻塞的,不适合高并发场景。
  • 在Spring 5中已标记为不推荐使用,建议使用WebClient代替。
示例代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}
}@Service
public class ApiService {@Autowiredprivate RestTemplate restTemplate;public String getExample() {String url = "http://example.com/api";return restTemplate.getForObject(url, String.class);}public String postExample(Object request) {String url = "http://example.com/api";return restTemplate.postForObject(url, request, String.class);}
}

2. WebClient

WebClient 是 Spring 5 引入的一个非阻塞、响应式的 HTTP 客户端,适用于异步请求。

优点
  • 非阻塞,适合高并发和异步场景。
  • 功能强大,支持多种HTTP方法和数据格式。
  • 适用于响应式编程模型,能够与Project Reactor无缝集成。
缺点
  • 学习曲线相对较高,代码较为复杂。
示例代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;@Configuration
public class WebClientConfig {@Beanpublic WebClient.Builder webClientBuilder() {return WebClient.builder();}
}@Service
public class ApiService {@Autowiredprivate WebClient.Builder webClientBuilder;public Mono<String> getExample() {String url = "http://example.com/api";return webClientBuilder.build().get().uri(url).retrieve().bodyToMono(String.class);}public Mono<String> postExample(Object request) {String url = "http://example.com/api";return webClientBuilder.build().post().uri(url).bodyValue(request).retrieve().bodyToMono(String.class);}
}

3. AsyncRestTemplate

AsyncRestTemplate 是 Spring 提供的一个用于异步 HTTP 请求的客户端。

优点
  • 支持异步请求,可以提高并发性能。
缺点
  • 复杂性较高,使用时需要处理ListenableFuture
  • 在Spring 5中已标记为不推荐使用,建议使用WebClient代替。
示例代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.util.concurrent.ListenableFuture;@Configuration
public class AsyncRestTemplateConfig {@Beanpublic AsyncRestTemplate asyncRestTemplate() {return new AsyncRestTemplate();}
}@Service
public class ApiService {@Autowiredprivate AsyncRestTemplate asyncRestTemplate;public ListenableFuture<String> getExample() {String url = "http://example.com/api";return asyncRestTemplate.getForEntity(url, String.class);}public ListenableFuture<String> postExample(Object request) {String url = "http://example.com/api";return asyncRestTemplate.postForEntity(url, request, String.class);}
}

4. RestTemplate vs WebClient vs AsyncRestTemplate

特性RestTemplateWebClientAsyncRestTemplate
类型同步异步/非阻塞异步
性能较低(阻塞)高(非阻塞)较高(异步)
使用复杂度中等中等
推荐使用场景简单的同步HTTP请求高并发、异步处理已有代码需异步处理
Spring 5支持情况不推荐推荐不推荐

总结

在Spring Boot中,RestTemplate适用于简单的同步请求,WebClient适用于高并发和异步处理场景,而AsyncRestTemplate则可以用于已有代码需要异步处理的场景。根据具体的应用需求选择合适的工具可以提高代码的性能和可维护性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/16237.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vxe-table v4 ~ v4.6 升级到 v4.7+ 版本

vxe-table v4 ~ v4.6 升级到 v4.7 版本 更新日志 vxe-table 4.7 分离了 vxe-table 表格和 vxe-pc-ui 组件库 变动如下 全局安装 // ... import VxeUITable from vxe-table import vxe-table/lib/style.css // ...createApp(App).use(VxeUITable).mount(#app)修改后 // ...i…

数据结构(五)

数据结构&#xff08;五&#xff09; 常见的排序算法内部排序交换插入选择归并基数 外部排序基于归并的 常见的排序算法 内部排序 交换 冒泡&#xff1a;每一次运行总会将最小的或者最大的放到前面&#xff0c;如果需要交换&#xff0c;一直在交换 快速排序*&#xff1a;经过…

【java程序设计期末复习】chapter5 子类的继承

子类的继承 继承是一种由已有的类创建新类的机制。利用继承&#xff0c;我们可以先创建一个共有属性的一般类&#xff0c;根据该一般类再创建具有特殊属性的新类&#xff0c;新类继承一般类的状态和行为&#xff0c;并根据需要增加它自己的新的状态和行为。由继承而得到的类称…

Git分支的操作详解(查看、新增、切换、合并、删除)

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…

2024最新前端面试八股文【基础篇293题】

⼀、HTML、HTTP、web综合问题 1 前端需要注意哪些SEO 2 <img> 的 title 和 alt 有什么区别 3 HTTP的⼏种请求⽅法⽤途 4 从浏览器地址栏输⼊url到显示⻚⾯的步骤 5 如何进⾏⽹站性能优化 6 HTTP状态码及其含义 7 语义化的理解 8 介绍⼀下你对浏览器内核的理解 9 …

【操作系统】发展与分类(手工操作、批处理、分时操作、实时操作)

2.操作系统发展与分类 思维导图 手工操作阶段&#xff08;此阶段无操作系统&#xff09; 需要人工干预 缺点&#xff1a; 1.用户独占全机&#xff0c;资源利用率低&#xff1b; 2.CPU等待手工操作&#xff0c;CPU利用不充分。 批处理阶段&#xff08;操作系统开始出现&#x…

链表-线性表的链式表示

链表-线性表的链式表示 #mermaid-svg-ozpXrKnNCyYdqHvN {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-ozpXrKnNCyYdqHvN .error-icon{fill:#552222;}#mermaid-svg-ozpXrKnNCyYdqHvN .error-text{fill:#552222;stro…

express 设定路径别名

在使用ts情况下 pnpm i -D tsconfig-paths配置tsconfig.json {// 引入 tsconfig-paths/register// 注意 ts-node 的层级与 compilerOptions 相同"ts-node": {"require": ["tsconfig-paths/register"]},"compilerOptions": {// ...//…

width: auto 和 width: 100% 的区别

width: auto Vs. width: 100% 关于 width 属性 CSS 中的 width 属性用于设置元素的宽度。默认情况下&#xff0c;width 设置的是内容区&#xff08;content area&#xff09;的宽度。如果元素有样式 box-sizing: border-box&#xff0c;则 width 设置的是边框区&#xff08;bo…

正运动控制器:视觉纠偏和找孔

一、用户主界面CCD参数设置 通过主界面CCD参数设置&#xff0c;学习如何操作计算相机中心与电批中心的偏移量&#xff0c;以及相机标定的功能。 1、相机中心与电批中心的偏移量计算 1.1、在用户主界面点击CCD参数按钮&#xff0c;进入CCD设置界面。 主界面 CCD参数设置界面 1…

制作电子画册速成攻略,快来试试

​当今社会&#xff0c;数字媒体日益普及&#xff0c;电子画册作为一种崭新的展示方式&#xff0c;受到了越来越多人的青睐。它不仅形式新颖&#xff0c;互动性强&#xff0c;而且制作起来也并不复杂。想知道如何快速掌握制作电子画册的技巧吗&#xff1f;我来教你吧。 接下来&…

二叉树的广义表反序列化

前言 个人小记 一、代码 #include<stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define MAX_NODE 10 #define MAX_LEN 100 #define key(n)(n)?(n->key):(-1) typedef struct Node {int key;struct Node* lchild,*rchil…

Leetcode 3159. Find Occurrences of an Element in an Array

Leetcode 3159. Find Occurrences of an Element in an Array 1. 解题思路2. 代码实现 题目链接&#xff1a;3159. Find Occurrences of an Element in an Array 1. 解题思路 这一题的话我们只需要首先统计一下array当中目标元素x出现在第几次的位置&#xff0c;构造一个has…

推荐13款常用的Vscode插件,提高前端日常开发效率

1. Live Server Live Server 插件是一个用于前端开发的扩展&#xff0c;它的主要作用是提供一个本地开发服务器&#xff0c;以便实时预览和调试网页应用程序。其最大特点在于热重载&#xff0c;即开发者可实时预览代码效果。 因为Live Server 允许开发者在浏览器中实时预览您正…

软件测试面试题(五)

一&#xff1a;如何选择用户测试的工作产品&#xff1f;、 答&#xff1a;在用户有需求得到签字确认以后&#xff0c;我们选择用户测试的工作产品。我们几乎所有的项目都进行了测试&#xff0c;我们是在项目立项公告中得知需要对工作产品进行测试。 二&#xff1a;测试环境描述…

C++中集合的使用

在 C 中&#xff0c;集合通常指的是标准模板库&#xff08;STL&#xff09;中的 std::set 或 std::unordered_set。这两个都是用来存储不重复元素的容器&#xff0c;但在实现和使用方式上有一些区别。 1. std::set&#xff1a; 基于红黑树实现&#xff0c;元素按照严格的顺序…

Llama 3没能逼出GPT-5!OpenAI怒“卷”To B战场,新企业级 AI 功能重磅推出!

Meta 是本周当之无愧的AI巨星&#xff01;刚刚推出的 Llama 3 凭借着强大的性能和开源生态的优势在 LLM 排行榜上迅速跃升。 按理说&#xff0c;Llama 3在开源的状态下做到了 GPT-3.7 的水平&#xff0c;必然会显得用户&#xff08;尤其是企业用户&#xff0c;他们更具备独立部…

指令中常用的7种寻址方式z

指令中的寻址方式就是对指令中的地址字段进行解释&#xff0c;以获得操作数的方法或获得程序转移地址的方法。常用的寻址方式有&#xff1a; 立即寻址&#xff1a;操作数就包含在指令中。直接寻址&#xff1a;操作数存放在内存单元中&#xff0c;指令中直接给出操作数所在存储…

C#调用HttpClient.SendAsync报错:System.Net.Http.HttpRequestException: 发送请求时出错。

C#调用HttpClient.SendAsync报错&#xff1a;System.Net.Http.HttpRequestException: 发送请求时出错。 var response await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);问题出在SSL/TLS&#xff0c;Windows Server 2012不支持…