SpringBoot3 实现webclient 通用方法
SpringBoot3 实现webclient 通用方法
Spring Boot WebClient是Spring Framework 5中引入的一个新的响应式Web客户端,用于异步和响应式地与外部服务进行通信。它是基于Project Reactor的响应式编程模型构建的,提供了比传统的RestTemplate更现代和强大的功能。本文将详细介绍如何在Spring Boot 3中实现WebClient的通用方法。
前言
Spring Boot WebClient是Spring Framework 5中引入的一个新的响应式Web客户端,用于异步和响应式地与外部服务进行通信。它是基于Project Reactor的响应式编程模型构建的,提供了比传统的RestTemplate更现代和强大的功能。
介绍
响应式编程模型:WebClient是基于响应式编程模型的,这意味着它可以非阻塞地执行网络请求,并且能够与流式数据交互。这使得WebClient在处理大量并发请求时具有更高的性能和可伸缩性。
异步操作:WebClient支持异步操作,这意味着它可以在等待网络响应的同时继续执行其他任务。这有助于提高应用程序的响应能力和吞吐量。
强大的API:WebClient提供了一个简洁而强大的API,用于构建HTTP请求和接收响应。它支持多种HTTP方法(如GET、POST、PUT、DELETE等),并提供了丰富的功能来处理请求头、请求体、响应体等。
流式处理:WebClient支持流式处理响应数据,这意味着它可以在接收响应数据的同时进行处理,而不需要将整个响应加载到内存中。这有助于处理大型响应数据,并减少内存使用。
错误处理:WebClient提供了强大的错误处理机制,可以方便地处理网络请求中出现的错误和异常情况。它支持自定义错误处理器,可以根据需要定义错误处理逻辑。
集成性:WebClient可以轻松地与Spring Boot的其他组件集成,如Spring Data、Spring Security等。这使得在构建基于微服务的响应式应用程序时更加方便和灵活。
替代RestTemplate:虽然RestTemplate在以前的Spring版本中广泛使用,但WebClient被视为其现代替代品。WebClient提供了更强大和灵活的功能,并且更适合与响应式编程模型一起使用。
一、引包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
二、通用方法
package com.zc.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.List;
/**
* @author zc
* @date 2024/4/15 16:52
* @desc
*/
@Component
public class WebClientUtil {
private final WebClient webClient;
@Autowired
public WebClientUtil(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.
baseUrl("http://127.0.0.1:30003").
build();
}
/**
* get方法
* @param url
* @param responseType
* @return
* @param
*/
public <T> T get(String url, Class<T> responseType) {
return webClient.get().
uri(url).
accept(MediaType.APPLICATION_JSON).
retrieve().
bodyToMono(responseType).
block();
}
/**
* get多条数据
* @param url
* @param responseType
* @return
* @param <T>
*/
public <T> List<T> list(String url, Class<T> responseType){
return webClient.get().
uri(url).
accept(MediaType.APPLICATION_JSON).
retrieve().
bodyToFlux(responseType).collectList().block();
}
/**
* post方法
* @param url
* @param requestBody
* @param responseType
* @return
* @param
*/
public <T> T post(String url, Object requestBody, Class<T> responseType) {
return webClient.post().
uri(url).
contentType(MediaType.APPLICATION_JSON).
bodyValue(requestBody).
accept(MediaType.APPLICATION_JSON).
retrieve().
bodyToMono(responseType).
block();
}
/**
* put方法
* @param url
* @param requestBody
* @param responseType
* @return
* @param
*/
public <T> T put(String url, Object requestBody, Class<T> responseType){
return webClient.put().
uri(url).
contentType(MediaType.APPLICATION_JSON).
bodyValue(requestBody).
accept(MediaType.APPLICATION_JSON).
retrieve().
bodyToMono(responseType).
block();
}
/**
* 删除方法
* @param url
* @param responseType
* @return
* @param
*/
public <T> T delete(String url, Class<T> responseType){
return webClient.delete().
uri(url).
accept(MediaType.APPLICATION_JSON).
retrieve().
bodyToMono(responseType).
block();
}
}
三、测试
客户端
import com.alibaba.fastjson.JSON;
import com.zc.Application;
import com.zc.bean.HostDiffBean;
import com.zc.util.WebClientUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.List;
/**
* @author zc
* @date 2024/2/23 10:40
* @desc
*/
@SpringBootTest(classes = Application.class)
public class TestFF {
@Autowired
private WebClientUtil webClientUtil;
@Test
public void test(){
List<HostDiffBean> list= webClientUtil.list("compare/hostInfo?pageSize=10&pageNum=1", HostDiffBean.class);
System.out.println(JSON.toJSON(list));
HostDiffBean hostDiffBean = new HostDiffBean();
hostDiffBean.setIp("127.0.0.1");
hostDiffBean.setHIp("127.0.0.2");
hostDiffBean.setCreateTime(new Date());
hostDiffBean.setSerialNumber("123");
hostDiffBean.setHDeviceNo("no123");
hostDiffBean.setDeviceNo("NO456");
String result = webClientUtil.post("compare/hostInfo/add", hostDiffBean, String.class);
System.out.println(result);
}
}
服务端
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.bean.*;
import com.neusoft.service.HostDataCompareService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author zc
* @date 2024/3/14 15:00
* @desc
*/
@RestController
@RequestMapping("/compare")
@Api(value = "数据对比接口", tags = "数据对比接口")
public class DataCompareController {
@Autowired
private HostDataCompareService hostDataCompareService;
@GetMapping("/hostInfo")
@ApiOperation(value = "宿主机数量差异查询", notes = "宿主机数量差异查询")
public List<HostInfoBean> getHostInfoBeans(@RequestParam(name = "pageSize") @Validated @ApiParam(value = "每页数", required = true) Integer pageSize,
@RequestParam(name = "pageNum") @Validated @ApiParam(value = "页数", required = true) Integer pageNum) {
Page<HostInfoBean> list = hostDataCompareService.getHostInfoBeans(pageSize, pageNum);
return list.getRecords();
}
@PostMapping("/hostInfo/add")
@ApiOperation(value = "宿主机数量差异查询", notes = "宿主机数量差异查询")
public String addHostInfoBeans(@RequestBody HostDiffBean hostDiffBean){
return "success";
}
}