Spring Framework 5.0 引入了 WebClient,这是一个新的非阻塞、响应式 Web 客户端 API,旨在为构建响应式微服务提供更好的支持。WebClient 是基于 Project Reactor 的响应式流 API 构建的,它可以高效地处理大量的并发请求,非常适合现代微服务架构。
WebClient 基于非阻塞 I/O,可以处理大量的并发请求而不会阻塞线程。WebClient 的行为,例如添加拦截器、过滤器或自定义转换器。WebClient 的工具,便于编写单元测试。下面是一个简单的示例,展示了如何使用 WebClient 发送一个 GET 请求并处理 JSON 响应。
import org.springframework.http.MediaType; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; public class WebClientExample { public static void main(String[] args) { // 创建 WebClient 实例 WebClient webClient = WebClient.create(); // 发送 GET 请求 webClient.get() .uri("http://example.com/api/data") .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Data.class) // 假设 Data 是一个 Java 类 .subscribe(data -> { System.out.println("Received data: " + data); }, error -> { System.err.println("Error occurred: " + error.getMessage()); }, () -> { System.out.println("Request completed."); }); } // 假设这是从服务器接收的数据类 static class Data { private String name; private int value; // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public String toString() { return "Data{" + "name='" + name + '\'' + ", value=" + value + '}'; } } } WebClient.create() 或者 WebClient.builder() 来创建 WebClient 实例。.get().uri("...") 或 .post().uri("...")。retrieve() 方法来处理响应。可以通过 .bodyToMono() 或 .bodyToFlux() 方法来转换响应体为 Mono 或 Flux。.subscribe() 方法来订阅 Mono 或 Flux 并处理数据。WebClient 可以通过多种方式来定制,例如添加拦截器、自定义转换器或设置超时时间等。
WebClient webClient = WebClient.builder() .filter((request, next) -> { // 自定义逻辑 return next.exchange(request); }) .build(); WebClient webClient = WebClient.builder() .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(16 * 1024 * 1024)) .build(); WebClient 提供了内置的异常处理机制,可以使用 onStatus 方法来处理特定的状态码。
webClient.get() .uri("http://example.com/api/data") .retrieve() .onStatus(HttpStatus::is4xxClientError, clientResponse -> { // 处理 4xx 错误 return clientResponse.bodyToMono(String.class) .map(body -> "Error: " + body); }) .bodyToMono(Data.class) .subscribe(data -> { System.out.println("Received data: " + data); }, error -> { System.err.println("Error occurred: " + error.getMessage()); }, () -> { System.out.println("Request completed."); }); WebClient 是一个强大且灵活的工具,非常适合现代响应式应用程序的需求。它提供了丰富的功能,使得发起 HTTP 请求和处理响应变得非常简单。如果你正在开发响应式或微服务应用程序,WebClient 是一个很好的选择。
上一篇:JVM相关流程的总结