SpringBoot3 RestTemplate配置與使用詳解
1. 簡介
RestTemplate 是 Spring 框架提供的一個用于發(fā)送 HTTP 請求的同步客戶端工具類。在 SpringBoot 3.x 版本中,我們依然可以使用 RestTemplate 來進(jìn)行 REST API 的調(diào)用。本文將詳細(xì)介紹如何在 SpringBoot 3 項目中配置和使用 RestTemplate。
2. 環(huán)境要求
- JDK 17+
- Spring Boot 3.x
- Maven/Gradle
3. 基礎(chǔ)配置
3.1 添加依賴
首先在pom.xml
中添加相關(guān)依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.5</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
3.2 RestTemplate配置類
創(chuàng)建一個配置類來注冊RestTemplate Bean:
package com.coderjia.springboot304web.config; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import java.time.Duration; /** * @author CoderJia * @create 2024/12/1 下午 04:24 * @Description **/ @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder .setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(5)) .build(); } }
4. 高級配置
4.1 自定義連接池配置
為了提高性能,我們可以使用 Apache HttpClient 連接池:
<dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.2.1</version> </dependency>
配置連接池:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(200); // 最大連接數(shù)為 200 connectionManager.setDefaultMaxPerRoute(20); // 每個路由的最大連接數(shù)為 20 CloseableHttpClient httpClient = HttpClients.custom() // 建 HTTP 客戶端 .setConnectionManager(connectionManager) .build(); // 創(chuàng)建請求工 HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); // 返回 RestTemplate return new RestTemplate(factory); } }
4.2 錯誤處理配置
自定義錯誤處理器:
public class CustomResponseErrorHandler implements ResponseErrorHandler { @Override public boolean hasError(ClientHttpResponse response) throws IOException { return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError(); } @Override public void handleError(ClientHttpResponse response) throws IOException { if (response.getStatusCode().is5xxServerError()) { throw new RuntimeException("服務(wù)器錯誤: " + response.getStatusCode()); } else if (response.getStatusCode().is4xxClientError()) { throw new RuntimeException("客戶端錯誤: " + response.getStatusCode()); } } }
將錯誤處理器添加到 RestTemplate:
@Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder .errorHandler(new CustomResponseErrorHandler()) .build(); }
5. 使用示例
5.1 RestTemplate方法列表
方法組 | 描述 |
---|---|
getForObject | 通過GET請求獲取資源的表示形式 |
getForEntity | 通過GET請求獲取ResponseEntity(包含狀態(tài)碼、請求頭和響應(yīng)體) |
headForHeaders | 通過HEAD請求獲取資源的所有請求頭信息 |
postForLocation | 通過POST請求創(chuàng)建新資源,并返回響應(yīng)中的Location頭信息 |
postForObject | 通過POST請求創(chuàng)建新資源,并返回響應(yīng)的表示形式 |
postForEntity | 通過POST請求創(chuàng)建新資源,并返回響應(yīng)的表示形式(包含完整的響應(yīng)信息) |
put | 通過PUT請求創(chuàng)建或更新資源 |
patchForObject | 通過PATCH請求更新資源并返回響應(yīng)的表示形式(注意:JDK的HttpURLConnection不支持PATCH,但Apache HttpComponents等支持) |
delete | 通過DELETE請求刪除指定URI的資源 |
optionsForAllow | 通過ALLOW請求獲取資源支持的HTTP方法 |
exchange | 更通用(且更靈活)的方法版本,提供額外的靈活性。接受RequestEntity作為輸入(包括HTTP方法、URL、請求頭和請求體),返回ResponseEntity。這些方法允許使用ParameterizedTypeReference代替Class來指定帶有泛型的響應(yīng)類型 |
execute | 執(zhí)行請求的最通用方式,通過回調(diào)接口可以完全控制請求準(zhǔn)備和響應(yīng)提取過程 |
這個表格展示了 RestTemplate 提供的所有主要方法,每個方法都有其特定的用途和場景。從簡單的GET請求到復(fù)雜的自定義請求處理,RestTemplate 都提供了相應(yīng)的支持。
5.2 基本使用
@Slf4j @RestController public class RestTemplateController { @Resource private RestTemplate restTemplate; // get @GetMapping("/get") public JSONObject get(@RequestParam("q1")String q1, @RequestParam("q2")String q2) { log.info("get"); String url = "https://echo.apifox.com/get"; return restTemplate.getForObject(url, JSONObject.class, q1, q2); } // post @GetMapping("/post") public JSONObject post(@RequestParam("q1")String q1, @RequestParam("q2")String q2) { log.info("post"); String url = "https://echo.apifox.com/post"; JSONObject body = new JSONObject(); body.put("q1", q1); body.put("q2", q2); return restTemplate.postForObject(url, body, JSONObject.class); } // delete @GetMapping("/delete") public String delete(@RequestParam("id") Long id) { log.info("delete"); String url = "https://echo.apifox.com/delete"; restTemplate.delete(url, id); return "Data deleted successfully!"; } // put @GetMapping("/put") public String put(@RequestParam("id") Long id, @RequestParam("name") String name) { log.info("put"); String url = "https://echo.apifox.com/put"; JSONObject body = new JSONObject(); body.put("id", id); body.put("name", name); restTemplate.put(url, body, id); return "Data updated successfully!"; } }
請求響應(yīng)
5.3 使用請求頭
public User getUserWithHeaders(Long id) { String url = "http://api.example.com/users/{id}"; HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer token123"); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<User> response = restTemplate.exchange( url, HttpMethod.GET, entity, User.class, id ); return response.getBody(); }
5.4 處理復(fù)雜響應(yīng)
@GetMapping("/getAnyThing") public JSONObject getList(@RequestParam("q1")String q1, @RequestParam("q2")String q2) { log.info("getAnyThing"); String url = "https://echo.apifox.com/post"; JSONObject jsonObject = new JSONObject(); jsonObject.put("q1", q1); jsonObject.put("q2", q2); HttpEntity<JSONObject> entity = new HttpEntity<>(jsonObject); // 定義了一個泛型類型的引用 typeRef,用于指定 restTemplate.exchange 方法返回的響應(yīng)體類型為 JSONObject。 ParameterizedTypeReference<JSONObject> typeRef = new ParameterizedTypeReference<>() { }; ResponseEntity<JSONObject> response = restTemplate.exchange( url, HttpMethod.POST, entity, typeRef ); return response.getBody(); }
5.5 打印日志攔截器
package com.coderjia.springboot304web.config; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; /** * @author CoderJia * @create 2024/12/1 下午 05:02 * @Description **/ @Slf4j public class LoggingInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { log.info("Request: " + request.getMethod() + " " + request.getURI()); ClientHttpResponse response = execution.execute(request, body); log.info("Response: " + response.getStatusCode()); return response; } }
RestTemplate設(shè)置攔截器:
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new LoggingInterceptor()); RestTemplate build = builder .errorHandler(new CustomResponseErrorHandler()) .build(); build.setInterceptors(interceptors);
6. 最佳實踐
- 超時設(shè)置:始終設(shè)置合適的連接超時和讀取超時時間。
- 錯誤處理:實現(xiàn)自定義的錯誤處理器來處理異常情況。
- 連接池:在高并發(fā)場景下使用連接池來提升性能。
- 重試機(jī)制:對于不穩(wěn)定的服務(wù),考慮添加重試機(jī)制。
- 日志記錄:添加適當(dāng)?shù)娜罩居涗泚砀櫿埱蠛晚憫?yīng)。
7. 注意事項
- RestTemplate 在 Spring 5.0 之后被標(biāo)記為維護(hù)模式,建議在新項目中考慮使用 WebClient。
- 在生產(chǎn)環(huán)境中,要注意設(shè)置合理的超時時間和連接池參數(shù)。
- 處理響應(yīng)時要注意檢查響應(yīng)狀態(tài)和錯誤處理。
- 使用 HTTPS 時需要適當(dāng)配置SSL證書。
8. 總結(jié)
本文詳細(xì)介紹了在 SpringBoot 3.x 中如何配置和使用 RestTemplate,包括基本配置、高級配置以及各種使用場景。雖然 RestTemplate 目前處于維護(hù)模式,但它仍然是一個穩(wěn)定且易用的HTTP客戶端工具。對于新項目,也可以考慮使用響應(yīng)式的WebClient作為替代方案。
參考資料
到此這篇關(guān)于SpringBoot3 RestTemplate配置與使用詳解的文章就介紹到這了,更多相關(guān)SpringBoot3 RestTemplate配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot使用RestTemplate實現(xiàn)HTTP請求詳解
- SpringBoot中RestTemplate的使用詳解
- springboot中的RestTemplate使用詳解
- SpringBoot使用RestTemplate的示例詳解
- Springboot使用RestTemplate調(diào)用第三方接口的操作代碼
- Springboot之restTemplate的配置及使用方式
- SpringBoot 如何使用RestTemplate發(fā)送Post請求
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- Springboot RestTemplate 簡單使用解析
相關(guān)文章
JAVAEE model1模型實現(xiàn)商品瀏覽記錄(去除重復(fù)的瀏覽記錄)(一)
這篇文章主要為大家詳細(xì)介紹了JAVAEE model1模型實現(xiàn)商品瀏覽記錄,去除重復(fù)的瀏覽記錄,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11spring AOP自定義注解方式實現(xiàn)日志管理的實例講解
下面小編就為大家分享一篇spring AOP自定義注解方式實現(xiàn)日志管理的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01VsCode配置java環(huán)境的詳細(xì)圖文教程
vscode是一個免費(fèi)的代碼編輯器,支持多種主題,應(yīng)用起來簡單方便,下面這篇文章主要給大家介紹了關(guān)于VsCode配置java環(huán)境的詳細(xì)圖文教程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02