SpringBoot3实现webclient的通用方法详解

 更新时间:2024年04月17日 09:52:22   作者:面壁者-扬  
Spring Boot WebClient 是 Spring Framework 5 中引入的一个新的响应式 Web 客户端,用于异步和响应式地与外部服务进行通信,下面我们就来看看SpringBoot3实现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";
    }
}

结果:

四、参考

SpringBoot - 网络请求客户端WebClient使用详解

以上就是SpringBoot3实现webclient的通用方法详解的详细内容,更多关于SpringBoot3 webclient的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:

相关文章

  • pagehelper踩坑记之分页乱套问题解决

    pagehelper踩坑记之分页乱套问题解决

    这篇文章主要为大家介绍了pagehelper踩坑记之分页乱套问题解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • @JsonFormat 和 @DateTimeFormat 时间格式化注解(场景示例代码)

    @JsonFormat 和 @DateTimeFormat 时间格式化注解(场景示例代码)

    这篇文章主要介绍了@JsonFormat和@DateTimeFormat时间格式化注解,本文通过场景示例代码详解给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • java final本质详解

    java final本质详解

    在本篇文章里小编给大家分享的是关于java final本质的相关知识点内容,有需要的朋友们可以参考下。
    2019-09-09
  • 从零开始:快速入门SpringBoot注解的精髓

    从零开始:快速入门SpringBoot注解的精髓

    Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架,它通过使用注解来简化配置和开发过程,使开发人员能够更加专注于业务逻辑的实现,Spring Boot提供了许多注解,用于定义和配置应用程序的各个方面,需要的朋友可以参考下
    2023-10-10
  • Spring中Bean的生命周期使用解析

    Spring中Bean的生命周期使用解析

    这篇文章主要介绍了Spring中Bean的生命周期使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • Java编程实现时间和时间戳相互转换实例

    Java编程实现时间和时间戳相互转换实例

    这篇文章主要介绍了什么是时间戳,以及Java编程实现时间和时间戳相互转换实例,具有一定的参考价值,需要的朋友可以了解下。
    2017-09-09
  • SSM项目中使用拦截器和过滤器的实现示例

    SSM项目中使用拦截器和过滤器的实现示例

    这篇文章主要介绍了SSM项目中使用拦截器和过滤器的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • Java数组高级算法与Arrays类常见操作小结【排序、查找】

    Java数组高级算法与Arrays类常见操作小结【排序、查找】

    这篇文章主要介绍了Java数组高级算法与Arrays类常见操作,结合实例形式总结分析了Java数组常见的排序算法、查找算法相关原理、实现与使用技巧,需要的朋友可以参考下
    2019-03-03
  • JavaWeb之Filter过滤器详解

    JavaWeb之Filter过滤器详解

    本篇文章主要介绍了JavaWeb之Filter过滤器详解,实例分析了JavaWeb之Filter过滤器的使用技巧,非常具有实用价值,需要的朋友可以参考下。
    2017-03-03
  • Java使用Poi导出Excel表格方法实例

    Java使用Poi导出Excel表格方法实例

    这篇文章主要给大家介绍了关于Java使用Poi导出Excel表格的相关资料,Java POI是一个用于操作Microsoft Office格式的Java API库,可以使用它来导出Excel文件,需要的朋友可以参考下
    2023-10-10

最新评论