给你 2 万条数据,怎么快速导入到 MySQL?写得太好了...

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 给你 2 万条数据,怎么快速导入到 MySQL?写得太好了...

一、前言

前两天做了一个导入的功能,导入开始的时候非常慢,导入2w条数据要1分多钟,后来一点一点的优化,从直接把list怼进Mysql中,到分配把list导入Mysql中,到多线程把list导入Mysql中。


时间是一点一点的变少了。非常的爽,最后变成了10s以内。


下面就展示一下过程。



二、直接把list怼进Mysql


使用mybatis的批量导入操作:

@Transactional(rollbackFor = Exception.class)
public int addFreshStudentsNew2(List<FreshStudentAndStudentModel> list, String schoolNo) {
    if (list == null || list.isEmpty()) {
        return 0;
    }
    List<StudentEntity> studentEntityList = new LinkedList<>();
    List<EnrollStudentEntity> enrollStudentEntityList = new LinkedList<>();
    List<AllusersEntity> allusersEntityList = new LinkedList<>();
    for (FreshStudentAndStudentModel freshStudentAndStudentModel : list) {
        EnrollStudentEntity enrollStudentEntity = new EnrollStudentEntity();
        StudentEntity studentEntity = new StudentEntity();
        BeanUtils.copyProperties(freshStudentAndStudentModel, studentEntity);
        BeanUtils.copyProperties(freshStudentAndStudentModel, enrollStudentEntity);
        String operator = TenancyContext.UserID.get();
        String studentId = BaseUuidUtils.base58Uuid();
        enrollStudentEntity.setId(BaseUuidUtils.base58Uuid());
        enrollStudentEntity.setStudentId(studentId);
        enrollStudentEntity.setIdentityCardId(freshStudentAndStudentModel.getIdCard());
        enrollStudentEntity.setOperator(operator);
        studentEntity.setId(studentId);
        studentEntity.setIdentityCardId(freshStudentAndStudentModel.getIdCard());
        studentEntity.setOperator(operator);
        studentEntityList.add(studentEntity);
        enrollStudentEntityList.add(enrollStudentEntity);
        AllusersEntity allusersEntity = new AllusersEntity();
        allusersEntity.setId(enrollStudentEntity.getId());
        allusersEntity.setUserCode(enrollStudentEntity.getNemtCode());
        allusersEntity.setUserName(enrollStudentEntity.getName());
        allusersEntity.setSchoolNo(schoolNo);
        allusersEntity.setTelNum(enrollStudentEntity.getTelNum());
        allusersEntity.setPassword(enrollStudentEntity.getNemtCode());  //密码设置为考生号
        allusersEntityList.add(allusersEntity);
    }
        enResult = enrollStudentDao.insertAll(enrollStudentEntityList);
        stuResult = studentDao.insertAll(studentEntityList);
        allResult = allusersFacade.insertUserList(allusersEntityList);
    if (enResult > 0 && stuResult > 0 && allResult) {
        return 10;
    }
    return -10;
}


Mapper.xml

<insert id="insertAll" parameterType="com.dmsdbj.itoo.basicInfo.entity.EnrollStudentEntity">
    insert into tb_enroll_student
    <trim prefix="(" suffix=")" suffixOverrides=",">
            id,  
            remark,  
            nEMT_aspiration,  
            nEMT_code,  
            nEMT_score,  
            student_id,  
            identity_card_id,  
            level,  
            major,  
            name,  
            nation,  
            secondary_college,  
            operator,  
            sex,  
            is_delete,  
            account_address,  
            native_place,  
            original_place,  
            used_name,  
            pictrue,  
            join_party_date,  
            political_status,  
            tel_num,  
            is_registry,  
            graduate_school,  
            create_time,  
            update_time        </trim>        
    values
    <foreach collection="list" item="item" index="index" separator=",">
    (
            #{item.id,jdbcType=VARCHAR},
            #{item.remark,jdbcType=VARCHAR},
            #{item.nemtAspiration,jdbcType=VARCHAR},
            #{item.nemtCode,jdbcType=VARCHAR},
            #{item.nemtScore,jdbcType=VARCHAR},
            #{item.studentId,jdbcType=VARCHAR},
            #{item.identityCardId,jdbcType=VARCHAR},
            #{item.level,jdbcType=VARCHAR},
            #{item.major,jdbcType=VARCHAR},
            #{item.name,jdbcType=VARCHAR},
            #{item.nation,jdbcType=VARCHAR},
            #{item.secondaryCollege,jdbcType=VARCHAR},
            #{item.operator,jdbcType=VARCHAR},
            #{item.sex,jdbcType=VARCHAR},
            0,
            #{item.accountAddress,jdbcType=VARCHAR},
            #{item.nativePlace,jdbcType=VARCHAR},
            #{item.originalPlace,jdbcType=VARCHAR},
            #{item.usedName,jdbcType=VARCHAR},
            #{item.pictrue,jdbcType=VARCHAR},
            #{item.joinPartyDate,jdbcType=VARCHAR},
            #{item.politicalStatus,jdbcType=VARCHAR},
            #{item.telNum,jdbcType=VARCHAR},
            #{item.isRegistry,jdbcType=TINYINT},
            #{item.graduateSchool,jdbcType=VARCHAR},
            now(),
            now()        
    )   
    </foreach>                
</insert> 


代码说明:

底层的mapper是通过逆向工程来生成的,批量插入如下,是拼接成类似:insert into tb_enroll_student()values (),()…….();


这样的缺点是,数据库一般有一个默认的设置,就是每次sql操作的数据不能超过4M。这样插入,数据多的时候,数据库会报错Packet for query is too large (6071393 > 4194304). You can change this value on the server by setting the max_allowed_packet' variable.,虽然我们可以通过


类似 修改 my.ini 加上 max_allowed_packet =6710886467108864=64M,默认大小4194304 也就是4M


修改完成之后要重启mysql服务,如果通过命令行修改就不用重启mysql服务。


完成本次操作,但是我们不能保证项目单次最大的大小是多少,这样是有弊端的。所以可以考虑进行分组导入。



三、分组把list导入Mysql中


同样适用mybatis批量插入,区别是对每次的导入进行分组计算,然后分多次进行导入:

@Transactional(rollbackFor = Exception.class)
public int addFreshStudentsNew2(List<FreshStudentAndStudentModel> list, String schoolNo) {
    if (list == null || list.isEmpty()) {
        return 0;
    }
    List<StudentEntity> studentEntityList = new LinkedList<>();
    List<EnrollStudentEntity> enrollStudentEntityList = new LinkedList<>();
    List<AllusersEntity> allusersEntityList = new LinkedList<>();
    for (FreshStudentAndStudentModel freshStudentAndStudentModel : list) {
        EnrollStudentEntity enrollStudentEntity = new EnrollStudentEntity();
        StudentEntity studentEntity = new StudentEntity();
        BeanUtils.copyProperties(freshStudentAndStudentModel, studentEntity);
        BeanUtils.copyProperties(freshStudentAndStudentModel, enrollStudentEntity);
        String operator = TenancyContext.UserID.get();
        String studentId = BaseUuidUtils.base58Uuid();
        enrollStudentEntity.setId(BaseUuidUtils.base58Uuid());
        enrollStudentEntity.setStudentId(studentId);
        enrollStudentEntity.setIdentityCardId(freshStudentAndStudentModel.getIdCard());
        enrollStudentEntity.setOperator(operator);
        studentEntity.setId(studentId);
        studentEntity.setIdentityCardId(freshStudentAndStudentModel.getIdCard());
        studentEntity.setOperator(operator);
        studentEntityList.add(studentEntity);
        enrollStudentEntityList.add(enrollStudentEntity);
        AllusersEntity allusersEntity = new AllusersEntity();
        allusersEntity.setId(enrollStudentEntity.getId());
        allusersEntity.setUserCode(enrollStudentEntity.getNemtCode());
        allusersEntity.setUserName(enrollStudentEntity.getName());
        allusersEntity.setSchoolNo(schoolNo);
        allusersEntity.setTelNum(enrollStudentEntity.getTelNum());
        allusersEntity.setPassword(enrollStudentEntity.getNemtCode());  //密码设置为考生号
        allusersEntityList.add(allusersEntity);
    }
    int c = 100;
    int b = enrollStudentEntityList.size() / c;
    int d = enrollStudentEntityList.size() % c;
    int enResult = 0;
    int stuResult = 0;
    boolean allResult = false;
    for (int e = c; e <= c * b; e = e + c) {
        enResult = enrollStudentDao.insertAll(enrollStudentEntityList.subList(e - c, e));
        stuResult = studentDao.insertAll(studentEntityList.subList(e - c, e));
        allResult = allusersFacade.insertUserList(allusersEntityList.subList(e - c, e));
    }
    if (d != 0) {
        enResult = enrollStudentDao.insertAll(enrollStudentEntityList.subList(c * b, enrollStudentEntityList.size()));
        stuResult = studentDao.insertAll(studentEntityList.subList(c * b, studentEntityList.size()));
        allResult = allusersFacade.insertUserList(allusersEntityList.subList(c * b, allusersEntityList.size()));
    }
    if (enResult > 0 && stuResult > 0 && allResult) {
        return 10;
    }
    return -10;
}

代码说明:

这样操作,可以避免上面的错误,但是分多次插入,无形中就增加了操作实践,很容易超时。所以这种方法还是不值得提倡的。

再次改进,使用多线程分批导入。



四、多线程分批导入Mysql

依然使用mybatis的批量导入,不同的是,根据线程数目进行分组,然后再建立多线程池,进行导入。


@Transactional(rollbackFor = Exception.class)
public int addFreshStudentsNew(List<FreshStudentAndStudentModel> list, String schoolNo) {
    if (list == null || list.isEmpty()) {
        return 0;
    }
    List<StudentEntity> studentEntityList = new LinkedList<>();
    List<EnrollStudentEntity> enrollStudentEntityList = new LinkedList<>();
    List<AllusersEntity> allusersEntityList = new LinkedList<>();
    list.forEach(freshStudentAndStudentModel -> {
        EnrollStudentEntity enrollStudentEntity = new EnrollStudentEntity();
        StudentEntity studentEntity = new StudentEntity();
        BeanUtils.copyProperties(freshStudentAndStudentModel, studentEntity);
        BeanUtils.copyProperties(freshStudentAndStudentModel, enrollStudentEntity);
        String operator = TenancyContext.UserID.get();
        String studentId = BaseUuidUtils.base58Uuid();
        enrollStudentEntity.setId(BaseUuidUtils.base58Uuid());
        enrollStudentEntity.setStudentId(studentId);
        enrollStudentEntity.setIdentityCardId(freshStudentAndStudentModel.getIdCard());
        enrollStudentEntity.setOperator(operator);
        studentEntity.setId(studentId);
        studentEntity.setIdentityCardId(freshStudentAndStudentModel.getIdCard());
        studentEntity.setOperator(operator);
        studentEntityList.add(studentEntity);
        enrollStudentEntityList.add(enrollStudentEntity);
        AllusersEntity allusersEntity = new AllusersEntity();
        allusersEntity.setId(enrollStudentEntity.getId());
        allusersEntity.setUserCode(enrollStudentEntity.getNemtCode());
        allusersEntity.setUserName(enrollStudentEntity.getName());
        allusersEntity.setSchoolNo(schoolNo);
        allusersEntity.setTelNum(enrollStudentEntity.getTelNum());
        allusersEntity.setPassword(enrollStudentEntity.getNemtCode());  //密码设置为考生号
        allusersEntityList.add(allusersEntity);
    });
    int nThreads = 50;
    int size = enrollStudentEntityList.size();
    ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
    List<Future<Integer>> futures = new ArrayList<Future<Integer>>(nThreads);
    for (int i = 0; i < nThreads; i++) {
        final List<EnrollStudentEntity> EnrollStudentEntityImputList = enrollStudentEntityList.subList(size / nThreads * i, size / nThreads * (i + 1));
        final List<StudentEntity> studentEntityImportList = studentEntityList.subList(size / nThreads * i, size / nThreads * (i + 1));
        final List<AllusersEntity> allusersEntityImportList = allusersEntityList.subList(size / nThreads * i, size / nThreads * (i + 1));
       Callable<Integer> task1 = () -> {
      studentSave.saveStudent(EnrollStudentEntityImputList,studentEntityImportList,allusersEntityImportList);
           return 1;
        };
      futures.add(executorService.submit(task1));
    }
    executorService.shutdown();
    if (!futures.isEmpty() && futures != null) {
        return 10;
    }
    return -10;
}

代码说明:


上面是通过应用ExecutorService 建立了固定的线程数,然后根据线程数目进行分组,批量依次导入。一方面可以缓解数据库的压力,另一个面线程数目多了,一定程度会提高程序运行的时间。


缺点就是要看服务器的配置,如果配置好的话就可以开多点线程,配置差的话就开小点。


五、小结

通过使用这个操作真是不断的提高了,项目使用技巧也是不错。


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
6天前
|
canal 消息中间件 关系型数据库
Canal作为一款高效、可靠的数据同步工具,凭借其基于MySQL binlog的增量同步机制,在数据同步领域展现了强大的应用价值
【9月更文挑战第1天】Canal作为一款高效、可靠的数据同步工具,凭借其基于MySQL binlog的增量同步机制,在数据同步领域展现了强大的应用价值
66 4
|
15天前
|
关系型数据库 MySQL 数据库
RDS MySQL灾备服务协同解决方案构建问题之数据库备份数据的云上云下迁移如何解决
RDS MySQL灾备服务协同解决方案构建问题之数据库备份数据的云上云下迁移如何解决
|
9天前
|
SQL 存储 缓存
MySQL是如何保证数据不丢失的?
文章详细阐述了InnoDB存储引擎中Buffer Pool与DML操作的关系。在执行插入、更新或删除操作时,InnoDB为了减少磁盘I/O,会在Buffer Pool中缓存数据页进行操作,随后将更新后的“脏页”刷新至磁盘。为防止服务宕机导致数据丢失,InnoDB采用了日志先行(WAL)机制,通过将DML操作记录为Redo Log并异步刷新到磁盘,结合双写机制和合理的日志刷新策略,确保数据的持久性和一致性。尽管如此,仍需合理配置参数以平衡性能与数据安全性。
MySQL是如何保证数据不丢失的?
|
11天前
|
关系型数据库 MySQL 大数据
教你使用Python玩转MySQL数据库,大数据导入不再是难题!
教你使用Python玩转MySQL数据库,大数据导入不再是难题!
|
7天前
|
存储 关系型数据库 MySQL
|
7天前
|
SQL 关系型数据库 MySQL
SQL Server、MySQL、PostgreSQL:主流数据库SQL语法异同比较——深入探讨数据类型、分页查询、表创建与数据插入、函数和索引等关键语法差异,为跨数据库开发提供实用指导
【8月更文挑战第31天】SQL Server、MySQL和PostgreSQL是当今最流行的关系型数据库管理系统,均使用SQL作为查询语言,但在语法和功能实现上存在差异。本文将比较它们在数据类型、分页查询、创建和插入数据以及函数和索引等方面的异同,帮助开发者更好地理解和使用这些数据库。尽管它们共用SQL语言,但每个系统都有独特的语法规则,了解这些差异有助于提升开发效率和项目成功率。
63 0
|
16天前
|
SQL 关系型数据库 MySQL
【揭秘】MySQL binlog日志与GTID:如何让数据库备份恢复变得轻松简单?
【8月更文挑战第22天】MySQL的binlog日志记录数据变更,用于恢复、复制和点恢复;GTID为每笔事务分配唯一ID,简化复制和恢复流程。开启binlog和GTID后,可通过`mysqldump`进行逻辑备份,包含binlog位置信息,或用`xtrabackup`做物理备份。恢复时,使用`mysql`命令执行备份文件,或通过`innobackupex`恢复物理备份。GTID模式下的主从复制配置更简便。
69 2
|
11天前
|
弹性计算 关系型数据库 数据库
手把手带你从自建 MySQL 迁移到云数据库,一步就能脱胎换骨
阿里云瑶池数据库来开课啦!自建数据库迁移至云数据库 RDS原来只要一步操作就能搞定!点击阅读原文完成实验就可获得一本日历哦~
|
12天前
|
人工智能 小程序 关系型数据库
【MySQL】黑悟空都掌握的技能,数据库隔离级别全攻略
本文以热门游戏《黑神话:悟空》为契机,深入浅出地解析了数据库事务的四种隔离级别:读未提交、读已提交、可重复读和串行化。通过具体示例,展示了不同隔离级别下的事务行为差异及可能遇到的问题,如脏读、不可重复读和幻读等。此外,还介绍了在MySQL中设置隔离级别的方法,包括全局和会话级别的调整,并通过实操演示了各隔离级别下的具体效果。本文旨在帮助开发者更好地理解和运用事务隔离级别,以提升数据库应用的一致性和性能。
78 2
【MySQL】黑悟空都掌握的技能,数据库隔离级别全攻略
|
17天前
|
数据可视化 关系型数据库 MySQL
Mysql8 如何在 Window11系统下完成跳过密钥校验、完成数据库密码的修改?
这篇文章介绍了如何在Windows 11系统下跳过MySQL 8的密钥校验,并通过命令行修改root用户的密码。
Mysql8 如何在 Window11系统下完成跳过密钥校验、完成数据库密码的修改?

热门文章

最新文章

下一篇
DDNS