class="hide-preCode-box">

2、发起 POST 请求
对于 POST 请求,可以发送 JSON 数据:

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class ApiService {

    private final WebClient webClient;

    public ApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public String postData(Object requestData) {
        return webClient.post()
                .uri("/submit")
                .body(Mono.just(requestData), Object.class)
                .retrieve()
                .bodyToMono(String.class)
                .block();
    }
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"> class="hide-preCode-box">

五、优化和最佳实践
1、超时设置
为避免长时间等待,建议为 WebClient 配置超时时间:

import java.time.Duration;

@Bean
public WebClient webClientWithTimeout(WebClient.Builder builder) {
    return builder
            .baseUrl("https://api.example.com")
            .defaultHeaders(headers -> headers.set("Authorization", "Bearer token"))
            .build()
            .mutate()
            .responseTimeout(Duration.ofSeconds(5)) // 设置响应超时时间
            .build();
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">

2、 使用拦截器
拦截器可以用于日志记录或添加全局参数:

@Bean
public WebClient.Builder webClientBuilder() {
    return WebClient.builder()
            .filter((request, next) -> {
                System.out.println("Request: " + request.url());
                return next.exchange(request);
            });
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">

3、异步调用
WebClient 原生支持异步编程,适合处理高并发请求场景:

public Mono<String> fetchDataAsync() {
    return webClient.get()
            .uri("/data")
            .retrieve()
            .bodyToMono(String.class);
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">

六、错误处理
1、使用 onStatus 处理 HTTP 错误
WebClient 提供了灵活的错误处理机制:

import org.springframework.web.reactive.function.client.WebClientResponseException;

public String fetchWithErrorHandling() {
    return webClient.get()
            .uri("/data")
            .retrieve()
            .onStatus(status -> status.is4xxClientError(),
                response -> Mono.error(new RuntimeException("Client error!")))
            .onStatus(status -> status.is5xxServerError(),
                response -> Mono.error(new RuntimeException("Server error!")))
            .bodyToMono(String.class)
            .block();
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">

2、捕获异常
可以通过 doOnError 捕获并处理异常:

public Mono<String> fetchWithExceptionHandling() {
    return webClient.get()
            .uri("/data")
            .retrieve()
            .bodyToMono(String.class)
            .doOnError(e -> {
                if (e instanceof WebClientResponseException) {
                    WebClientResponseException ex = (WebClientResponseException) e;
                    System.err.println("Error response: " + ex.getResponseBodyAsString());
                }
            });
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">

结语
WebClient 是一个功能强大且灵活的 HTTP 客户端,适合在高并发场景下替代 RestTemplate 使用。在实际项目中,通过合理的配置和优化,可以显著提高服务间通信的效率和可靠性。

data-report-view="{"mod":"1585297308_001","spm":"1001.2101.3001.6548","dest":"https://blog.csdn.net/weixin_46619605/article/details/144372375","extend1":"pc","ab":"new"}">>
注:本文转载自blog.csdn.net的小马不敲代码的文章"https://blog.csdn.net/weixin_46619605/article/details/144372375"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接

评论记录:

未查询到任何数据!