`
234390216
  • 浏览: 10193491 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
博客专栏
A5ee55b9-a463-3d09-9c78-0c0cf33198cd
Oracle基础
浏览量:460806
Ad26f909-6440-35a9-b4e9-9aea825bd38e
springMVC介绍
浏览量:1771803
Ce363057-ae4d-3ee1-bb46-e7b51a722a4b
Mybatis简介
浏览量:1395429
Bdeb91ad-cf8a-3fe9-942a-3710073b4000
Spring整合JMS
浏览量:393886
5cbbde67-7cd5-313c-95c2-4185389601e7
Ehcache简介
浏览量:678220
Cc1c0708-ccc2-3d20-ba47-d40e04440682
Cas简介
浏览量:529293
51592fc3-854c-34f4-9eff-cb82d993ab3a
Spring Securi...
浏览量:1178733
23e1c30e-ef8c-3702-aa3c-e83277ffca91
Spring基础知识
浏览量:461882
4af1c81c-eb9d-365f-b759-07685a32156e
Spring Aop介绍
浏览量:150144
2f926891-9e7a-3ce2-a074-3acb2aaf2584
JAXB简介
浏览量:66849
社区版块
存档分类
最新评论

Spring Boot(14)——使用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

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

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics