Spring Boot 使用WebClient

使用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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值