SpringBoot+MybatisPlus+Mysql实现批量插入万级数据多种方式与耗时对比

本文主要是介绍SpringBoot+MybatisPlus+Mysql实现批量插入万级数据多种方式与耗时对比,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

场景

若依前后端分离版本地搭建开发环境并运行项目的教程:

若依前后端分离版手把手教你本地搭建环境并运行项目_本地运行若依前后端分离-CSDN博客

若依前后端分离版如何集成的mybatis以及修改集成mybatisplus实现Mybatis增强:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/136203040

基于以上基础,测试批量将万级以上数据插入到mysql数据中的多种方式。

注:

博客:
霸道流氓气质-CSDN博客

实现

1、数据准备

参考上面集成mp时测试用的SysStudent表以及相关代码,每种方式执行前首先将数据库中

表清空。

application.yml中连接mysql的url中添加开启批处理模式的配置

&rewriteBatchedStatements=true

2、方式一:最基本的for循环批量插入的方式

直接使用mapper自带的insert方法使用for循环插入数据

编写单元测试

    @Testpublic void foreachInsertData() {StopWatch stopWatch = new StopWatch();stopWatch.start();for (int i = 0; i < 50000; i++) {SysStudent sysStudent = SysStudent.builder().studentName("test").studentAge(i).studentHobby("test").build();sysStudentMapper.insert(sysStudent);}stopWatch.stop();System.out.println(stopWatch.shortSummary());}

运行结果

时间较长,高达179秒,不推荐使用。

利用for循环进行单条插入时,每次都是在获取连接(Connection)、释放连接和资源关闭等操作上,

(如果数据量大的情况下)极其消耗资源,导致时间长。

当然所有测试时间均是在单元测试中进行,运行时间受多方面影响,不代表最终业务层运行实际时间,

仅用作同等条件方式下耗时对比。

3、方式二:使用拼接sql方式实现批量插入数据

在mapper中新增方法

public interface SysStudentMapper extends BaseMapper<SysStudent>
{@Insert("<script>" +"insert into sys_student (student_name, student_age, student_hobby) values " +"<foreach collection='studentList' item='item' separator=','> " +"(#{item.studentName}, #{item.studentAge},#{item.studentHobby}) " +"</foreach> " +"</script>")int insertSplice(@Param("studentList") List<SysStudent> studentList);
}

编写单元测试

    @Testpublic void spliceSqlInsertData() {ArrayList<SysStudent> students = new ArrayList<>();StopWatch stopWatch = new StopWatch();stopWatch.start();for (int i = 0; i < 50000; i++) {SysStudent sysStudent = SysStudent.builder().studentName("test").studentAge(i).studentHobby("test").build();students.add(sysStudent);}sysStudentMapper.insertSplice(students);stopWatch.stop();System.out.println(stopWatch.shortSummary());}

运行结果

拼接结果就是将所有的数据集成在一条SQL语句的value值上,其由于提交到服务器上的insert语句少了,网络负载少了,

性能也就提上去。但是当数据量上去后,可能会出现内存溢出、解析SQL语句耗时等情况。

4、方式三:使用mybatisplus的saveBatch实现批量插入

使用MyBatis-Plus实现IService接口中批处理saveBatch()方法

编写单元测试

    @Testpublic void batchInsertData() {ArrayList<SysStudent> students = new ArrayList<>();StopWatch stopWatch = new StopWatch();stopWatch.start();for (int i = 0; i < 50000; i++) {SysStudent sysStudent = SysStudent.builder().studentName("test").studentAge(i).studentHobby("test").build();students.add(sysStudent);}iSysStudentService.saveBatch(students,1000);stopWatch.stop();System.out.println(stopWatch.shortSummary());}

运行结果

5、方式四:共用SqlSession,关闭自动提交事务实现for循环批量插入大数据量数据

由于同一个SqlSession省去对资源相关操作的耗能、减少对事务处理的时间等,从而极大程度上提高执行效率。

编写单元测试

    @Testpublic void forBatchInsertData() {//开启批处理处理模式 BATCH,关闭自动提交事务SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);//反射获取 MapperSysStudentMapper sysStudentMapper = sqlSession.getMapper(SysStudentMapper.class);StopWatch stopWatch = new StopWatch();stopWatch.start();for (int i = 0; i < 50000; i++) {SysStudent sysStudent = SysStudent.builder().studentName("test").studentAge(i).studentHobby("test").build();sysStudentMapper.insert(sysStudent);}//一次性提交事务sqlSession.commit();//关闭资源sqlSession.close();stopWatch.stop();System.out.println(stopWatch.shortSummary());}

引入依赖

    @Autowiredprivate SqlSessionFactory sqlSessionFactory;

运行结果

推荐使用

6、方式五:使用ThreadPoolTaskExecuror线程池实现批量插入大数据量数据到mysql

将要插入的数据列表按照指定的批次大小分割成多个子列表,并开启多个线程来执行插入操作。

通过 TransactionManager 获取事务管理器,并使用 TransactionDefinition 定义事务属性。

在每个线程中,我们通过 transactionManager.getTransaction() 方法获取事务状态,并在插入操作中使用该状态来管理事务。

在插入操作完成后,根据操作结果调用transactionManager.commit()或 transactionManager.rollback() 方法来提交或回滚事务。

在每个线程执行完毕后,都会调用 CountDownLatch 的 countDown() 方法,以便主线程等待所有线程都执行完毕后再返回。

Java中使用CountDownLatch实现并发流程控制:

Java中使用CountDownLatch实现并发流程控制_countdownlatch设置为几-CSDN博客

SpringBoot中使用Spring自带线程池ThreadPoolTaskExecutor与Java8CompletableFuture实现异步任务示例:

SpringBoot中使用Spring自带线程池ThreadPoolTaskExecutor与Java8CompletableFuture实现异步任务示例_spring boot taskexecutor-CSDN博客

编写单元测试:

    @Testpublic void threadPoolInsertData() {ArrayList<SysStudent> students = new ArrayList<>();StopWatch stopWatch = new StopWatch();stopWatch.start();for (int i = 0; i < 50000; i++) {SysStudent sysStudent = SysStudent.builder().studentName("test").studentAge(i).studentHobby("test").build();students.add(sysStudent);}int count = students.size();int pageSize = 1000; //每批次插入的数据量int threadNum = count%pageSize == 0?(count/pageSize):(count/pageSize+1); //线程数CountDownLatch countDownLatch = new CountDownLatch(threadNum);for (int i = 0; i < threadNum; i++) {int startIndex = i * pageSize;int endIndex = Math.min(count,(i+1)*pageSize);List<SysStudent> subList = students.subList(startIndex,endIndex);threadPoolTaskExecutor.execute(()->{DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();TransactionStatus status = transactionManager.getTransaction(transactionDefinition);try{sysStudentMapper.insertSplice(subList);transactionManager.commit(status);}catch (Exception exception){transactionManager.rollback(status);throw exception;}finally {countDownLatch.countDown();}});}try{countDownLatch.await();}catch (InterruptedException e){e.printStackTrace();}stopWatch.stop();System.out.println(stopWatch.shortSummary());}

需要引入依赖

    @Autowiredprivate ThreadPoolTaskExecutor threadPoolTaskExecutor;@Autowiredprivate PlatformTransactionManager transactionManager;

运行结果

推荐使用



      

这篇关于SpringBoot+MybatisPlus+Mysql实现批量插入万级数据多种方式与耗时对比的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/735894

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

MySQL 中的 CAST 函数详解及常见用法

《MySQL中的CAST函数详解及常见用法》CAST函数是MySQL中用于数据类型转换的重要函数,它允许你将一个值从一种数据类型转换为另一种数据类型,本文给大家介绍MySQL中的CAST... 目录mysql 中的 CAST 函数详解一、基本语法二、支持的数据类型三、常见用法示例1. 字符串转数字2. 数字

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依