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 Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

MySQL 8 中的一个强大功能 JSON_TABLE示例详解

《MySQL8中的一个强大功能JSON_TABLE示例详解》JSON_TABLE是MySQL8中引入的一个强大功能,它允许用户将JSON数据转换为关系表格式,从而可以更方便地在SQL查询中处理J... 目录基本语法示例示例查询解释应用场景不适用场景1. ‌jsON 数据结构过于复杂或动态变化‌2. ‌性能要

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

MySQL字符串常用函数详解

《MySQL字符串常用函数详解》本文给大家介绍MySQL字符串常用函数,本文结合实例代码给大家介绍的非常详细,对大家学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql字符串常用函数一、获取二、大小写转换三、拼接四、截取五、比较、反转、替换六、去空白、填充MySQL字符串常用函数一、

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A