多线程之批量插入

背景

昨天在测试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. TCP/IP协议(一)网络基础知识 网络七层协议

    参考书籍为<图解tcp/ip>-第五版.这篇随笔,主要内容还是TCP/IP所必备的基础知识,包括计算机与网络发展的历史及标准化过程(简述).OSI参考模型.网络概念的本质.网络构建的设备等 ...

  2. jvm理论-class文件

    当JVM运行Java程序的时候,它会加载对应的class文件,并提取class文件中的信息存放在JVM的方法区内存中. Class文件组成 1.Class文件是一组以8位字节为基础单位的二进制流,各个 ...

  3. ArrayList代码学习

    ArrayList (数组链表)使用Object数组作为存储. /** * The array buffer into which the elements of the ArrayList are ...

  4. Convert ResultSet to JSON and XML

    public static JSONArray convertToJSON(ResultSet resultSet) throws Exception { JSONArray jsonArray = ...

  5. centos 中查找文件、目录、内容

    1.查找文件 find / -name 'filename'12.查找目录 find / -name 'path' -type d13.查找内容 find . | xargs grep -ri 'co ...

  6. 【Android自己定义控件】圆圈交替,仿progress效果

    还是我们自定View的那几个步骤: 1.自己定义View的属性 2.在View的构造方法中获得我们自己定义的属性 3.重写onMesure (不是必须) 4.重写onDraw 自己定义View的属性 ...

  7. 【MySQL】MySQL中查询出数据表中存在重复的值list

    1.目的:查询MySQL数据表中,重复记录的值 2.示例: 3.代码: select serial_num,count(*) as count FROM card_ticket GROUP BY se ...

  8. Android开发导出apk报错:Unable to build: the file dx.jar was not loaded from the SDK folder

    问题背景 此问题一般出现在,同时使用了Eclipse和Android Studio,eclipse是不会去下载最新的Android的相关tools,但是studio有时候会自动更新最新的build-t ...

  9. Visual Studio 2015 msvsmon.exe crashed when c++ debugging with x64

    Completely uninstalling Astrill fixed the issue but this solution is not what I want. Astrill suppor ...

  10. ffmpeg中av_log的实现分析

    [时间:2017-10] [状态:Open] [关键词:ffmpeg,avutil,av_log, 日志输出] 0 引言 FFmpeg的libavutil中的日志输出的接口整体比较少,但是功能还是不错 ...