多线程之批量插入

背景

昨天在测试mysql的两种批量更新时,由于需要入库大量测试数据,反复执行插入脚本,过程繁琐,档次很低,测试完后我就想着写个批量插入的小demo,然后又想写个多线程的批量插入的demo,然后就有了下面的东西了……

环境

spring-boot 1.5.6 集成 mysql druid mybits 还有一些无关紧要的东西

代码

线程类:
/**
 * @ClassName InsertDataThread
 * @Description <
插入数据类>
 * @Author zhaiyt
 * @Date 2018/8/29 17:04
 * @Version 1.0
 */
public class InsertDataThread extends Thread {     //日志
   
private final Logger logger = LoggerFactory.getLogger(InsertDataThread.class);     //数据访问层
   
private UserEntityMapper userEntityMapper;     //具体插入批次
   
private int batch;     //插入的数据
   
private List<UserEntity> list;     public InsertDataThread(UserEntityMapper userMpper, List<UserEntity> li, int batch) {
        this.userEntityMapper = userMpper;
        this.list = li;
        this.batch = batch;
    }     @Override
    public void run() {
        try {
            this.userEntityMapper.insertBatch(this.list);
            logger.info("" + this.batch + "批次插入成功");
        } catch (Exception e) {
            logger.error("" + this.batch + "批次插入失败");
        }     }
}

===============================================================================

service层的多线程批量插入方法:

/**
 * @param
list
 
* @return int
 * @Description <
批量插入>
 * @Author zhaiyt
 * @Date 9:51 2018/8/29
 * @Param [list]
 */
@Override
public int insertBatch(List<UserEntity> list) throws Exception {
    PageHelper.offsetPage(0, 500000);
    long start = System.currentTimeMillis();
    List<UserEntity> listUser = userEntityMapper.selectAllUser();
    int betch = 0;
        if (CollectionUtils.isEmpty(listUser)) {
        logger.error("表中无数据,需要改造测试");
        return 0;
    }
    //根据数据量判断是否使用多线程 选择开启线程数
   
if (listUser.size() > 1000000) {
        betch = 10;
    } else if (listUser.size() > 100000) {
        betch = 5;
    } else if (listUser.size() > 10000) {
        betch = 3;
    } else {
        //不走多线程
       
long end = System.currentTimeMillis();
        logger.error("查询耗时:" + (end - start));
        start = System.currentTimeMillis();
        int count = userEntityMapper.insertBatch(listUser);
        end = System.currentTimeMillis();
        logger.error("插入耗时:" + (end - start));
        return count;
    }     //计数器
   
int size = 0;
    //创建线程池
   
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(betch);     for (int i = 0; i < (Math.ceil(listUser.size() / 5000)); i++) {
        int startLen = i * 5000;
        int endLen = ((i + 1) * 5000 > listUser.size() ? listUser.size() - 1 : (i + 1) * 5000);
        // 该线程处理
        List<UserEntity> threadList = listUser.subList(startLen, endLen);
        size = size + threadList.size();
        fixedThreadPool.execute(new InsertDataThread(userEntityMapper, threadList, i));
    }
    System.err.println("插入数据总条数:" + size);
    long end = System.currentTimeMillis();
    logger.error("查询耗时:" + (end - start));
    return size;
}

项目路径:https://git.lug.ustc.edu.cn/zhaiyt/threadInsertDemo

多线程之批量插入小demo的更多相关文章

  1. Java多线程同步问题:一个小Demo完全搞懂

    版权声明:本文出自汪磊的博客,转载请务必注明出处. Java线程系列文章只是自己知识的总结梳理,都是最基础的玩意,已经掌握熟练的可以绕过. 一.一个简单的Demo引发的血案 关于线程同步问题我们从一个 ...

  2. c#批量插入数据库Demo

    using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...

  3. java线程间通信:一个小Demo完全搞懂

    版权声明:本文出自汪磊的博客,转载请务必注明出处. Java线程系列文章只是自己知识的总结梳理,都是最基础的玩意,已经掌握熟练的可以绕过. 一.从一个小Demo说起 上篇我们聊到了Java多线程的同步 ...

  4. C#中使用SqlBulkCopy的批量插入和OracleBulkCopy的批量插入

    1.首先我们做一下准备工作,在sql server和oracle分别建立一个Student表 oracle中 --创建Student表 -- create table Student( stuId n ...

  5. Visual Studio 2017 - Windows应用程序打包成exe文件(2)- Advanced Installer 关于Newtonsoft.Json,LINQ to JSON的一个小demo mysql循环插入数据、生成随机数及CONCAT函数 .NET记录-获取外网IP以及判断该IP是属于网通还是电信 Guid的生成和数据修整(去除空格和小写字符)

    Visual Studio 2017 - Windows应用程序打包成exe文件(2)- Advanced Installer   Advanced Installer :Free for 30 da ...

  6. 多线程查询数据,将结果存入到redis中,最后批量从redis中取数据批量插入数据库中【我】

    多线程查询数据,将结果存入到redis中,最后批量从redis中取数据批量插入数据库中 package com.xxx.xx.reve.service; import java.util.ArrayL ...

  7. Mybatis 批量插入和更新小例

    SpringBoot配置Mybatis前文有博文,数据库mysql: package com.example.demo.biz.dto; public class User { private int ...

  8. Python多线程Threading爬取图片,保存本地,openpyxl批量插入图片到Excel表中

    之前用过openpyxl库保存数据到Excel文件写入不了,换用xlsxwriter 批量插入图片到Excel表中 1 import os 2 import requests 3 import re ...

  9. [小干货]SqlBulkCopy简单封装,让批量插入更方便

    关于 SqlServer 批量插入的方式,前段时间也有大神给出了好几种批量插入的方式及对比测试(http://www.cnblogs.com/jiekzou/p/6145550.html),估计大家也 ...

随机推荐

  1. 转自: linux svn命令行无法拉取中文名称的文件

    转自: https://blog.csdn.net/shaohui/article/details/3996274#commentBox svn: Can't convert string from  ...

  2. [Vuex] Perform Async Updates using Vuex Actions with TypeScript

    Mutations perform synchronous modifications to the state, but when it comes to make an asynchronous ...

  3. mysql5 数据库连接丢失问题,autoReconnect=true不起作用

    The last packet successfully received from the server was 55,404,563 millise 方案1 定时器 方案2 修改连接池容量 mys ...

  4. Win10系统的SurfacePro4如何重装系统-2 重装WIN10系统

    把SurfacePro充好电,然后关机,开机按住音量+,然后再按电源键,可以开机并进入BIOS(此前应确保优盘已经装了PE并插入Surface)   然后选择U盘启动为第一个(按住之后把他拖放到第一位 ...

  5. linux下安装EJBCA 搭建私有CA服务器

    linux下安装EJBCA 搭建私有CA服务器 EJBCA是一个全功能的JAVA的CA系统软件,我们可以用此搭建私有CA服务器: 一:首先我的测试环境: 1.  linux mint18.3 62位: ...

  6. Nop--NopCommerce源码架构详解专题目录

    最近在研究外国优秀的ASP.NET mvc电子商务网站系统NopCommerce源码架构.这个系统无论是代码组织结构.思想及分层都值得我们学习.对于没有一定开发经验的人要完全搞懂这个源码还是有一定的难 ...

  7. Easyui中 messager.alert 后某文本框获得焦点

    messager.alert 后某文本框获得焦点 $.messager.alert({ title:'消息', msg:'电话号码 只能是数字!', icon: 'info', width: 300, ...

  8. Effective Java 第三版——75. 在详细信息中包含失败捕获信息

    Tips 书中的源代码地址:https://github.com/jbloch/effective-java-3e-source-code 注意,书中的有些代码里方法是基于Java 9 API中的,所 ...

  9. django聚合查询

    聚合¶ Django 数据库抽象API 描述了使用Django 查询来增删查改单个对象的方法.然而,有时候你需要获取的值需要根据一组对象聚合后才能得到.这份指南描述通过Django 查询来生成和返回聚 ...

  10. MySQL 4 种隔离级别的区别

    ## 测试环境 mysql> select version(); +------------+ | version() | +------------+ -log | +------------ ...