1.简介
-  执行异步 HTTP 请求: WebClient允许你发送 GET、POST、PUT、DELETE 等各种 HTTP 请求,并且这些请求都是异步的,不会阻塞调用线程。
-  处理响应:你可以使用 WebClient来处理 HTTP 响应,包括获取响应体、响应头和状态码等信息。
-  请求和响应的编解码: WebClient支持自动编解码请求体和响应体,可以轻松地处理 JSON、XML 等格式的数据。
-  错误处理: WebClient提供了丰富的错误处理机制,可以处理各种 HTTP 相关的错误。
-  过滤器链和请求修改: WebClient允许你添加过滤器来修改或处理请求和响应,例如添加通用头信息、日志记录、请求重试等。
-  性能优化:由于 WebClient是非阻塞的,它可以显著提高应用程序的性能,特别是在处理大量并发请求时。
-  响应式编程: WebClient返回的是反应式类型(如Mono或Flux),这使得它可以很好地与反应式编程模型和其他反应式组件(如反应式数据库)集成。
-  测试: WebClient可以用于自动化测试,模拟 HTTP 请求和响应,以便测试应用程序的各个部分。
2.引入依赖
        <!-- wbeClient--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency>3.配置类WebClientConfig
baseUrl可以根据发起请求的路径的进行修改
package com.eco.thirdparty.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;@Configuration
public class WebClientConfig {@Beanpublic WebClient webClient(WebClient.Builder builder) {return builder.baseUrl("").defaultHeader("Content-Type", "application/json").defaultHeader("Accept", "application/json").build();}
}
4.具体代码:(以post发起携参请求获取数据为例)
Controller:
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {private final IUserService userService;@PostMapping("/sendWebClientRequest")public Result sendWebClientRequest(){Object sendWebClientRequest = userService.sendWebClientRequest();return Result.success(sendWebClientRequest);}}Service:
public interface IUserService extends IService<User> {Object sendWebClientRequest();}
ServiceImpl:
注意:如果在配置类中写了baseUrl那么此时相当于的webClient.uti(baseUrl + requestPath)
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {private final WebClient webClient;@Overridepublic Object sendWebClientRequest() {//发送请求的urlString requestPath = "http://localhost:8881/user/query";UserQuery userQuery = new UserQuery();userQuery.setGender(1);// 使用 block() 同步等待响应Mono<Object> responseMono = webClient.post().uri(requestPath).bodyValue(userQuery).retrieve().bodyToMono(Object.class);// 使用 block() 获取响应值Object resultJson = responseMono.block();// 如果需要,可以在这里处理 resultJsonSystem.out.println("Received data: " + resultJson);return resultJson;}
}