最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot 異步HTTP客戶端配置使用

 更新時間:2025年12月09日 10:07:28   作者:猩火燎猿  
本文詳細介紹SpringBoot中使用WebClient實現(xiàn)異步HTTP請求的完整方案,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1. 添加依賴

如果是 Spring Boot 2.x 或 3.x,WebClient 已包含在 spring-boot-starter-webflux 中:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2. WebClient 配置

可以通過 Bean 全局配置,也可以直接使用 WebClient.create()。

2.1 全局 Bean 配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {
    @Bean
    public WebClient webClient(WebClient.Builder builder) {
        return builder
                .baseUrl("https://api.example.com") // 可配置默認 baseUrl
                .build();
    }
}

2.2 自定義連接池和超時(高級配置)

import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;
import java.time.Duration;

@Bean
public WebClient webClient() {
    ConnectionProvider provider = ConnectionProvider.builder("custom")
        .maxConnections(100)
        .pendingAcquireTimeout(Duration.ofSeconds(60))
        .build();

    HttpClient httpClient = HttpClient.create(provider)
        .responseTimeout(Duration.ofSeconds(5));

    return WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .build();
}

3. 異步調(diào)用示例

WebClient 默認就是異步非阻塞的(基于 Reactor 響應(yīng)式流)。

3.1 GET 請求

@Autowired
private WebClient webClient;

public Mono<String> getDataAsync() {
    return webClient.get()
        .uri("/data")
        .retrieve()
        .bodyToMono(String.class);
}

3.2 POST 請求

public Mono<ResponseDto> postDataAsync(RequestDto request) {
    return webClient.post()
        .uri("/submit")
        .bodyValue(request)
        .retrieve()
        .bodyToMono(ResponseDto.class);
}

3.3 在 Controller 中使用

@RestController
public class DemoController {
    @Autowired
    private WebClient webClient;

    @GetMapping("/call-remote")
    public Mono<String> callRemote() {
        return webClient.get()
            .uri("/remote-api")
            .retrieve()
            .bodyToMono(String.class);
    }
}

4. 異步并發(fā)請求

比如同時請求多個接口并合并結(jié)果:

Mono<String> call1 = webClient.get().uri("/api1").retrieve().bodyToMono(String.class);
Mono<String> call2 = webClient.get().uri("/api2").retrieve().bodyToMono(String.class);

Mono<Tuple2<String, String>> result = Mono.zip(call1, call2);

5. 錯誤處理

webClient.get().uri("/api")
    .retrieve()
    .onStatus(HttpStatus::isError, response -> 
        response.bodyToMono(String.class)
            .flatMap(errorBody -> Mono.error(new RuntimeException(errorBody)))
    )
    .bodyToMono(String.class);

6. 配置超時和連接池參數(shù)

如前文 2.2,使用 Reactor Netty 的 ConnectionProvider 和 HttpClient 可以靈活設(shè)置連接數(shù)、超時等。

7. 其他常見配置

  • 代理設(shè)置
  • SSL 配置
  • 請求/響應(yīng)日志
  • 攔截器(ExchangeFilterFunction)

例如日志攔截器:

WebClient.builder()
    .filter((request, next) -> {
        System.out.println("Request: " + request.url());
        return next.exchange(request);
    })
    .build();

8. 與 Spring MVC Controller 集成

如果你用的是 Spring MVC Controller,可以用 Mono<T> 或 Flux<T> 作為返回值,Spring Boot 會自動處理響應(yīng)式類型。

9. 自定義請求頭、參數(shù)、Cookie

設(shè)置請求頭/參數(shù):

webClient.get()
    .uri(uriBuilder -> uriBuilder
        .path("/search")
        .queryParam("keyword", "spring")
        .build())
    .header("Authorization", "Bearer xxx")
    .cookie("SESSIONID", "abcdefg")
    .retrieve()
    .bodyToMono(String.class);

10. 全局異常處理與重試機制

全局異常處理:

可以通過 ExchangeFilterFunction 實現(xiàn)全局異常攔截與處理:

@Bean
public WebClient webClient() {
    return WebClient.builder()
        .filter((request, next) -> next.exchange(request)
            .flatMap(response -> {
                if (response.statusCode().isError()) {
                    return response.bodyToMono(String.class)
                        .flatMap(errorBody -> Mono.error(new RuntimeException(errorBody)));
                }
                return Mono.just(response);
            }))
        .build();
}

重試機制(reactor-retry):

import reactor.util.retry.Retry;

webClient.get()
    .uri("/unstable-api")
    .retrieve()
    .bodyToMono(String.class)
    .retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(2)));

11. 文件上傳與下載(異步)

文件上傳(multipart/form-data):

import org.springframework.core.io.FileSystemResource;

FileSystemResource file = new FileSystemResource("/path/to/file.txt");

webClient.post()
    .uri("/upload")
    .contentType(MediaType.MULTIPART_FORM_DATA)
    .body(BodyInserters.fromMultipartData("file", file))
    .retrieve()
    .bodyToMono(String.class);

文件下載:

webClient.get()
    .uri("/download")
    .retrieve()
    .bodyToFlux(DataBuffer.class)
    .map(dataBuffer -> {
        // 將 DataBuffer 寫入文件
        // 省略具體實現(xiàn)
        return dataBuffer;
    });

12. 與服務(wù)發(fā)現(xiàn)、負載均衡集成

如果用 Spring Cloud,可直接注入帶負載均衡的 WebClient:

import org.springframework.cloud.client.loadbalancer.LoadBalanced;

@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
    return WebClient.builder();
}

// 使用
@Autowired
private WebClient.Builder webClientBuilder;

webClientBuilder.build()
    .get()
    .uri("http://service-name/api")
    .retrieve()
    .bodyToMono(String.class);

這里的 service-name 是注冊中心(如 Eureka、Nacos)中的服務(wù)名,WebClient 會自動負載均衡。

13. 與 OAuth2 等安全機制集成

Spring Security 提供了對 OAuth2 的支持,可以自動為 WebClient 請求加上 Token。

import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction;

@Bean
public WebClient webClient(ReactiveOAuth2AuthorizedClientManager manager) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth2 = 
        new ServerOAuth2AuthorizedClientExchangeFilterFunction(manager);
    return WebClient.builder()
        .apply(oauth2.oauth2Configuration())
        .build();
}

14. WebClient 性能調(diào)優(yōu)建議

  • 連接池參數(shù)調(diào)整合理設(shè)置最大連接數(shù)、每主機最大連接數(shù)、連接超時等
  • 響應(yīng)式編程配合線程池對于非響應(yīng)式 Controller 推薦 @Async 或線程池配合
  • 避免阻塞操作在響應(yīng)式流中避免 block(),否則會失去異步性能優(yōu)勢
  • 合理的重試和超時防止雪崩和資源耗盡

15. 常見問題解答

Q1:WebClient 如何同步調(diào)用?A:可以用 .block(),但這會阻塞線程,失去異步優(yōu)勢。一般只在測試或特殊場景下使用。

Q2:如何打印 WebClient 的請求和響應(yīng)日志?A:可通過 ExchangeFilterFunction 實現(xiàn),或配置日志框架:

logging.level.reactor.netty.http.client=DEBUG

Q3:WebClient 與 RestTemplate 區(qū)別?

  • RestTemplate 是同步阻塞的
  • WebClient 是異步非阻塞的,支持響應(yīng)式流
  • 官方推薦新項目優(yōu)先用 WebClient

總結(jié)

  • 推薦使用 WebClient 作為 Spring Boot 異步 HTTP 客戶端
  • 支持靈活配置連接池、超時、代理、SSL 等
  • 默認就是異步非阻塞
  • 適合高并發(fā)、微服務(wù)場景
  • WebClient 支持豐富的異步 HTTP 場景,配置靈活
  • 可與 Spring Cloud、Spring Security 等生態(tài)無縫集成
  • 適合微服務(wù)、網(wǎng)關(guān)、爬蟲等高并發(fā)異步場景

到此這篇關(guān)于Spring Boot 異步HTTP客戶端配置使用的文章就介紹到這了,更多相關(guān)Spring Boot 異步HTTP內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot多環(huán)境(dev、test、prod)配置詳解

    springboot多環(huán)境(dev、test、prod)配置詳解

    這篇文章主要介紹了springboot多環(huán)境(dev、test、prod)配置詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-04-04
  • SpringBoot整合Log4j2實現(xiàn)自定義日志打印失效的原因及解決

    SpringBoot整合Log4j2實現(xiàn)自定義日志打印失效的原因及解決

    本文給大家介紹了關(guān)于SpringBoot項目整合Log4j2實現(xiàn)自定義日志打印失效原因及解決辦法,主要的原因是因為SpringBoot的logback包的存在,文中通過圖文給大家了詳細解決方法,需要的朋友可以參考下
    2024-01-01
  • Kotlin語言編程Regex正則表達式實例詳解

    Kotlin語言編程Regex正則表達式實例詳解

    這篇文章主要為大家介紹了Kotlin語言編程Regex正則表達式實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • Hibernate組件映射代碼詳解

    Hibernate組件映射代碼詳解

    這篇文章主要介紹了Hibernate組件映射代碼詳解,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-02-02
  • 關(guān)于Java?獲取時間戳的方法

    關(guān)于Java?獲取時間戳的方法

    這篇文章主要介紹了關(guān)于Java獲取時間戳的方法,Java有兩個取時間戳的方法,分別是System.currentTimeMillis()和System.nanoTime()下文對兩種方法進行詳細介紹,需要的小伙伴可以參考一下
    2022-04-04
  • Spring Boot 中的 @PutMapping 注解原理及使用小結(jié)

    Spring Boot 中的 @PutMapping 注解原理及使用小結(jié)

    在本文中,我們介紹了 Spring Boot 中的 @PutMapping 注解,它可以將 HTTP PUT 請求映射到指定的處理方法上,我們還介紹了 @PutMapping 注解的原理以及如何在 Spring Boot 中使用它,感興趣的朋友跟隨小編一起看看吧
    2023-12-12
  • 淺談SpringBoot如何自定義Starters

    淺談SpringBoot如何自定義Starters

    今天帶大家來學(xué)習(xí)SpringBoot如何自定義Starters,文中有非常詳細的圖文介紹及代碼示例,對正在學(xué)習(xí)java的小伙伴們很有幫助,需要的朋友可以參考下
    2021-05-05
  • 解析Java設(shè)計模式編程中命令模式的使用

    解析Java設(shè)計模式編程中命令模式的使用

    這篇文章主要介紹了Java設(shè)計模式編程中命令模式的使用,在一些處理請求響應(yīng)的場合經(jīng)??梢杂玫矫钅J降木幊趟悸?需要的朋友可以參考下
    2016-02-02
  • 一文詳解springboot中的熱啟動配置方案

    一文詳解springboot中的熱啟動配置方案

    SpringBoot的熱啟動主要通過 **`spring-boot-devtools`** 模塊實現(xiàn),能在代碼修改后自動重啟應(yīng)用,大幅提升開發(fā)效率,下面小編就來和大家講講詳細配置和使用指南
    2025-07-07
  • JDK動態(tài)代理原理:只能代理接口,不能代理類問題

    JDK動態(tài)代理原理:只能代理接口,不能代理類問題

    這篇文章主要介紹了JDK動態(tài)代理原理:只能代理接口,不能代理類問題。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11

最新評論

凌源市| 丰镇市| 富源县| 苍溪县| 太和县| 鄯善县| 双辽市| 汶川县| 右玉县| 福清市| 策勒县| 纳雍县| 亳州市| 化德县| 克拉玛依市| 富顺县| 久治县| 页游| 鄂伦春自治旗| 泾阳县| 车险| 沈阳市| 浮山县| 西畴县| 马关县| 昌邑市| 大庆市| 界首市| 曲靖市| 峨边| 恭城| 加查县| 习水县| 张家港市| 乾安县| 宁晋县| 石阡县| 和林格尔县| 无棣县| 明溪县| 内江市|