您现在的位置是:首页 > 文章详情

Spring Boot(14)——使用WebClient

日期:2019-01-04点击:434

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

(注:本文基于Spring Boot 2.0.3所写)

原文链接:https://yq.aliyun.com/articles/684425
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章