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

相关文章

MySQL常用字符串函数示例和场景介绍

《MySQL常用字符串函数示例和场景介绍》MySQL提供了丰富的字符串函数帮助我们高效地对字符串进行处理、转换和分析,本文我将全面且深入地介绍MySQL常用的字符串函数,并结合具体示例和场景,帮你熟练... 目录一、字符串函数概述1.1 字符串函数的作用1.2 字符串函数分类二、字符串长度与统计函数2.1

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Oracle数据库定时备份脚本方式(Linux)

《Oracle数据库定时备份脚本方式(Linux)》文章介绍Oracle数据库自动备份方案,包含主机备份传输与备机解压导入流程,强调需提前全量删除原库数据避免报错,并需配置无密传输、定时任务及验证脚本... 目录说明主机脚本备机上自动导库脚本整个自动备份oracle数据库的过程(建议全程用root用户)总结

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

MySQL 内存使用率常用分析语句

《MySQL内存使用率常用分析语句》用户整理了MySQL内存占用过高的分析方法,涵盖操作系统层确认及数据库层bufferpool、内存模块差值、线程状态、performance_schema性能数据... 目录一、 OS层二、 DB层1. 全局情况2. 内存占js用详情最近连续遇到mysql内存占用过高导致

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与