Spring Boot 使用 WebClient

WebClient是Spring WebFlux模块提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具,从Spring5.0开始提供。Spring Boot应用中添加如下依赖将自动添加Spring WebFlux依赖,从而可以使用WebClient。

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

Spring Boot的org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration.会自动配置一个WebClient.Builder类型的bean。在需要使用WebClient的时候在程序中注入一个WebClient.Builder对象,通过对它进行自定义来生成对应的WebClient对象,从而作为客户端进行Web请求。下面是一个简单的示例。

@Service
public class WebClientService {
    private final WebClient webClient;
  
    public WebClientService(WebClient.Builder builder) {
        this.webClient = builder.baseUrl("http://localhost:8081").build();
    }
  
    public String getJson() {
        return this.webClient.get().uri("hello/json").retrieve().bodyToMono(String.class).block();
    }
  
}

WebClientCustomizer

Spring Boot提供了org.springframework.boot.web.reactive.function.client.WebClientCustomizer接口定义,它允许我们通过实现该接口对WebClient进行一些通用的自定义,然后将该接口的实现类定义为Spring bean。Spring Boot在创建WebClient实例时会在bean容器中寻找WebClientCustomizer类型的bean,一一调用它们的customize()方法以便对WebClient进行一些自定义。下面的代码中就对WebClient添加了一个默认的Cookie和一个默认的Header。

@Component
public class MyWebClientCustomizer implements WebClientCustomizer {
    @Override
    public void customize(Builder webClientBuilder) {
        webClientBuilder.defaultCookie("cookieName", "cookieValue").defaultHeader("headerName", "headerValue");
    }
}

CodecCustomizer

如果需要定义自己的编解码工具,则可以实现org.springframework.boot.web.codec.CodecCustomizer接口,把它定义为Spring bean,通过其customize()方法可以获取到org.springframework.http.codec.CodecConfigurer对象,从而可以注册新的编解码工具,或对现有的编解码工具进行替换等。

本文主要介绍在Spring Boot工程中如何应用WebClient,关于WebClient的基本用法可以参考http://elim.iteye.com/blog/2427658