WebClient是Spring WebFlux模块提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具,从Spring5.0开始WebClient作为RestTemplete的替代品,有更好的响应式能力,支持异步调用,可以在Spring项目中实现网络请求。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.flygroupId>
<artifactId>web-clientartifactId>
<version>0.0.1version>
<name>basename>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<java.version>1.8java.version>
<skipTests>trueskipTests>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webfluxartifactId>
<version>5.2.3.RELEASEversion>
dependency>
<dependency>
<groupId>io.projectreactor.nettygroupId>
<artifactId>reactor-nettyartifactId>
<version>0.9.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-slf4j-implartifactId>
<version>2.12.1version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>3.10version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
<scope>providedscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.10.1version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>UTF-8encoding>
configuration>
plugin>
plugins>
build>
project>
log4j2.xml
<configuration status="off" monitorInterval="0">
<appenders>
<console name="Console" target="system_out">
<patternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
console>
appenders>
<loggers>
<root level="INFO">
<appender-ref ref="Console" />
root>
loggers>
configuration>
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
/**
* WebClient是RestTemplete的替代品,有更好的响应式能力,支持异步调用
*
* https://blog.csdn.net/zzhongcy/article/details/105412842
*
*/
@Slf4j
public class RunWebClient
{
public static void main(String[] args)
throws InterruptedException
{
// 默认使用netty
WebClient webClient = WebClient.builder()
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) // 缓冲区默认256k,解决报错Exceeded limit on max bytes to buffer : 262144
.build();
// block转换为同步调用
Mono<String> resp = WebClient.create().get().uri("https://00fly.online/upload/ids").acceptCharset(StandardCharsets.UTF_8).accept(MediaType.TEXT_HTML).retrieve().bodyToMono(String.class);
String[] idArray = StringUtils.split(resp.block(), "\r\n");
log.info("★★★★★★★★ ids: {}", Arrays.asList(idArray));
// 异步调用
for (String id : idArray)
{
Mono<String> result = webClient.get()
.uri("https://blog.csdn.net/qq_16127313/article/details/{id}", id)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.acceptCharset(StandardCharsets.UTF_8)
.accept(MediaType.TEXT_HTML)
.retrieve()
.bodyToMono(String.class);
result.subscribe(body -> log.info("{} process complted", id), e -> log.error(e.getMessage()));
}
log.info("异步请求已提交...");
TimeUnit.SECONDS.sleep(10); // 重要,等待异步调用完成
}
}
如何使用下面的备份文件恢复成原始的项目代码,请移步查阅:神奇代码恢复工具
//goto pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fly</groupId>
<artifactId>web-client</artifactId>
<version>0.0.1</version>
<name>base</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<skipTests>true</skipTests>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.9.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
//goto src\main\java\com\fly\http\RunWebClient.java
package com.fly.http;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;
/**
* WebClient是RestTemplete的替代品,有更好的响应式能力,支持异步调用
*
* https://blog.csdn.net/zzhongcy/article/details/105412842
*
*/
@Slf4j
public class RunWebClient
{
public static void main(String[] args)
throws InterruptedException
{
// 默认使用netty
WebClient webClient = WebClient.builder()
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(-1)) // 缓冲区默认256k,解决报错Exceeded limit on max bytes to buffer : 262144
.build();
// block转换为同步调用
Mono<String> resp = WebClient.create().get().uri("https://00fly.online/upload/ids").acceptCharset(StandardCharsets.UTF_8).accept(MediaType.TEXT_HTML).retrieve().bodyToMono(String.class);
String[] idArray = StringUtils.split(resp.block(), "\r\n");
log.info("★★★★★★★★ ids: {}", Arrays.asList(idArray));
// 异步调用
for (String id : idArray)
{
Mono<String> result = webClient.get()
.uri("https://blog.csdn.net/qq_16127313/article/details/{id}", id)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.acceptCharset(StandardCharsets.UTF_8)
.accept(MediaType.TEXT_HTML)
.retrieve()
.bodyToMono(String.class);
result.subscribe(body -> log.info("{} process complted", id), e -> log.error(e.getMessage()));
}
log.info("异步请求已提交...");
TimeUnit.SECONDS.sleep(10); // 重要,等待异步调用完成
}
}
//goto src\main\resources\log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="off" monitorInterval="0">
<appenders>
<console name="Console" target="system_out">
<patternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</console>
</appenders>
<loggers>
<root level="INFO">
<appender-ref ref="Console" />
</root>
</loggers>
</configuration>
有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!
-over-