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.pswp.cn/bicheng/16237.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/16237.shtml
英文地址,請注明出處:http://en.pswp.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不支持…