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

2023-10-30

一、前言

前两天做了一个导入的功能,导入开始的时候非常慢,导入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.

<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 建立了固定的线程数,然后根据线程数目进行分组,批量依次导入。一方面可以缓解数据库的压力,另一个面线程数目多了,一定程度会提高程序运行的时间。

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

五、小结

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

 
小伙伴们有兴趣想了解内容和更多相关学习资料的请点赞收藏+评论转发+关注我,后面会有很多干货。
我有一些面试题、架构、设计类资料可以说是程序员面试必备!所有资料都整理到网盘了,需要的话欢迎下载!私信我回复【07】即可免费获取

 

原文出处:www.shaoqun.com/a/1601159.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • 使用 Checkstyle Plugin 时从插件调用代码时出现问题:“org.eclipse.jface”

    我正在尝试在 Rational Software Architect 7 0 0 4 上使用 eclipse cs 插件 我最近卸载了旧的 beta2 版本并安装了 beta3 插件本身按照之前的配置工作 但是每当我尝试通过 Windows
  • 使用 Spring 时实例化对象,用于测试与生产

    使用 Spring 时 应该使用 Spring 配置 xml 来实例化生产对象 并在测试时直接实例化对象 这样的理解是否正确 Eg MyMain java package org world hello import org springf
  • 如何解决 onEditCommit 事件上的类型不匹配错误?

    我在 Fxml 中使用 onEditCommit 事件在用户编辑数据后检索数据 FXML 代码
  • Laravel Group By 和 Order By 不起作用

    我尝试制作一个Laravel 5 8项目 项目中的数据是这样的 id purch name prcvalue 1 10234 Nabila 100 2 10234 Nadeera 450 3 10234 Nabila 540 4 10234
  • Spring Stomp over Websocket:流式传输大文件

    我的SockJs客户端在网页中 发送帧大小为16K的消息 消息大小限制决定了我可以传输的文件的最大大小 以下是我在文档中找到的内容 Configure the maximum size for an incoming sub protoco
  • 所有junit测试后的清理

    在我的项目中 我必须在所有测试之前进行一些存储库设置 这是使用一些棘手的静态规则来完成的 然而 在所有测试之后我不知道如何进行清理 我不想保留一些神奇的静态数字来引用所有测试方法的数量 我应该一直维护它 最受赞赏的方法是添加一些侦听器 该侦
  • 使用 java 按电子邮件发送日历邀请

    我正在尝试使用 java 发送每封电子邮件的日历邀请 收件人收到电子邮件 但不会显示接受或拒绝的邀请 而是将该事件自动添加到他的日历中 我正在使用 ical4j jar 构建活动 邀请 private Calendar getInvite
  • @EnableTransactionManagement 的范围是什么?

    我试图了解正确的放置位置 EnableTransactionManagement多个 JavaConfig 上下文的情况下的注释 考虑以下场景 我在 JPAConfig java 和 AppConfig java 中有 JPA 配置以及一组
  • 从数据库 MYSQL 和 Codeigniter 获取信息

    如果你们需要其他信息 上一个问题就在这里 从数据库中获取信息 https stackoverflow com questions 13336744 fetching information from the database 另一个更新 尽
  • 打印包含 JBIG2 图像的 PDF

    请推荐一些库 帮助我打印包含 JBIG2 编码图像的 PDF 文件 PDFRenderer PDFBox别帮我 这些库可以打印简单的 PDF 但不能打印包含 JBIG2 图像的 PDF PDFRenderer尝试修复它 根据 PDFRedn
  • 覆盖 MATLAB 默认静态 javaclasspath 的最佳方法

    MATLAB 配置为在搜索用户可修改的动态路径之前搜索其静态 java 类路径 不幸的是 静态路径包含相当多非常旧的公共库 因此如果您尝试使用新版本 您可能最终会加载错误的实现并出现错误 例如 静态路径包含 google collectio
  • jmap - 组织和堆操作会给 jvm 带来开销吗?

    正如标题所述 需要多少开销jmap histo and jmap heap分别带到jvm 如果一个内存敏感的 Java 进程处于OutOfMemory 例如 大约 96 的堆已满 并且无法通过 full gc 清除 其中一项操作是否有可能将
  • 使用 Java 从 S3 上的文件在 S3 上创建 zip 文件

    我在 S3 上有很多文件 需要对其进行压缩 然后通过 S3 提供压缩文件 目前 我将它们从流压缩到本地文件 然后再次上传该文件 这会占用大量磁盘空间 因为每个文件大约有 3 10MB 而且我必须压缩多达 100 000 个文件 所以一个 z
  • 我想要一个 Java 阿拉伯语词干分析器

    我正在寻找阿拉伯语的 Java 词干分析器 我找到了一个名为 AraMorph 的库 但它的输出是无法控制的 并且它会形成不需要的单词 还有其他阿拉伯语词干分析器吗 这是新的阿拉伯语词干分析器 Assem 的阿拉伯语轻词干分析器 http
  • struts 教程或示例

    我正在尝试在 Struts 中制作一个登录页面 这个想法是验证用户是否存在等 然后如果有错误 则返回到登录页面 错误显示为红色 典型的登录或任何表单页面验证 我想知道是否有人知道 Struts 中的错误管理教程 我正在专门寻找有关的教程 或
  • 为什么 BufferedWriter 不写入文件?

    我有这个代码 String strings Hi You He They Tetrabenzene Caaorine Calorine File file new File G words txt FileWriter fWriter Bu
  • 哪个是识别关系或非识别关系中的子表?

    在表之间的识别和非识别关系的上下文中 MySQL 文档大量将表称为父表和子表 如何判断哪个表是父表 哪个表是子表 子表 A K A 弱实体 http en wikipedia org wiki Weak entity 是一个表 其主键属性d
  • SQL:查找每个跑步者跑步之间的平均天数

    因此 如果我们给出下表 runner ran Carol 2011 02 01 Alice 2011 02 01 Bob 2011 02 01 Carol 2011 02 02 Bob 2011 02 02 Bob 2011 02 03 B
  • 使用 eclipse IDE 配置 angularjs

    我想开始使用 AngularJs 和 Java Spring 进行开发 我使用 Eclipse 作为 IDE 我想配置我的 Eclipse 以使这些框架无缝工作 我知道我可能要求太多 但相信我 我已经做了很多研究 你们是我最后的选择 任何帮
  • 尝试使用带有有效购买令牌的 Java Google Play Developer API v3 检索应用内购买信息时出现错误请求(无效值)

    当使用 Java Google Play Developer API 版本 3 并请求有效购买令牌的购买信息时 我收到以下异常 API 调用返回 400 Bad Request 响应以及以下消息 code 400 errors domain

随机推荐