目录
- 一,序言
- 二,简单示例
- 1. 引入依赖
- 2. 日志配置
- 3. 调用代码
- 4. 运行结果
- 三,完整代码
一,序言
WebClient是Spring WebFlux模块提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具,从Spring5.0开始WebClient作为RestTemplete的替代品,有更好的响应式能力,支持异步调用,可以在Spring项目中实现网络请求。
二,简单示例
1. 引入依赖
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>
2. 日志配置
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>
3. 调用代码
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的替代品,有更好的响应式能力,支持异步调用<br>* * https://blog.csdn.net/zzhongcy/article/details/105412842* */
@Slf4j
public class RunWebClient
{public static void main(String[] args)throws InterruptedException{// 默认使用nettyWebClient 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); // 重要,等待异步调用完成}
}
4. 运行结果
三,完整代码
如何使用下面的备份文件恢复成原始的项目代码,请移步查阅:神奇代码恢复工具
//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的替代品,有更好的响应式能力,支持异步调用<br>* * https://blog.csdn.net/zzhongcy/article/details/105412842* */
@Slf4j
public class RunWebClient
{public static void main(String[] args)throws InterruptedException{// 默认使用nettyWebClient 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-