百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

项目案例:Java多线程批量拆分List导入数据库

wptr33 2025-03-03 20:29 13 浏览

  • 一、前言
  • 二、直接把list怼进Mysql
  • 三、分组把list导入Mysql中
  • 四、多线程分批导入Mysql
  • 五、小结



一、前言

前两天做了一个导入的功能,导入开始的时候非常慢,导入2w条数据要1分多钟,后来一点一点的优化,从直接把list怼进Mysql中,到分配把list导入Mysql中,到多线程把list导入Mysql中。时间是一点一点的变少了。非常的爽,最后变成了10s以内。下面就展示一下过程。

二、直接把list怼进Mysql

使用mybatis的批量导入操作:

  @Transactional(rollbackFor = Exception.class)
    public int addFreshStudentsNew2(List list, String schoolNo) {
        if (list == null || list.isEmpty()) {
            return 0;
        }
        List studentEntityList = new LinkedList<>();
        List enrollStudentEntityList = new LinkedList<>();
        List 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 into tb_enroll_student
        
                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                
        values
        
        (
                #{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()        
        )   
                        
   

代码说明:

底层的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 =67108864,67108864=64M,默认大小4194304 也就是4M

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

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

三、分组把list导入Mysql中

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

 @Transactional(rollbackFor = Exception.class)
    public int addFreshStudentsNew2(List list, String schoolNo) {
        if (list == null || list.isEmpty()) {
            return 0;
        }
        List studentEntityList = new LinkedList<>();
        List enrollStudentEntityList = new LinkedList<>();
        List 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 list, String schoolNo) {
        if (list == null || list.isEmpty()) {
            return 0;
        }
        List studentEntityList = new LinkedList<>();
        List enrollStudentEntityList = new LinkedList<>();
        List 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> futures = new ArrayList>(nThreads);

        for (int i = 0; i < nThreads; i++) {
            final List EnrollStudentEntityImputList = enrollStudentEntityList.subList(size / nThreads * i, size / nThreads * (i + 1));
            final List studentEntityImportList = studentEntityList.subList(size / nThreads * i, size / nThreads * (i + 1));
            final List allusersEntityImportList = allusersEntityList.subList(size / nThreads * i, size / nThreads * (i + 1));

           Callable 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 建立了固定的线程数,然后根据线程数目进行分组,批量依次导入。一方面可以缓解数据库的压力,另一个面线程数目多了,一定程度会提高程序运行的时间。缺点就是要看服务器的配置,如果配置好的话就可以开多点线程,配置差的话就开小点.

相关推荐

redis的八种使用场景

前言:redis是我们工作开发中,经常要打交道的,下面对redis的使用场景做总结介绍也是对redis举报的功能做梳理。缓存Redis最常见的用途是作为缓存,用于加速应用程序的响应速度。...

基于Redis的3种分布式ID生成策略

在分布式系统设计中,全局唯一ID是一个基础而关键的组件。随着业务规模扩大和系统架构向微服务演进,传统的单机自增ID已无法满足需求。高并发、高可用的分布式ID生成方案成为构建可靠分布式系统的必要条件。R...

基于OpenWrt系统路由器的模式切换与网页设计

摘要:目前商用WiFi路由器已应用到多个领域,商家通过给用户提供一个稳定免费WiFi热点达到吸引客户、提升服务的目标。传统路由器自带的Luci界面提供了工厂模式的Web界面,用户可通过该界面配置路...

这篇文章教你看明白 nginx-ingress 控制器

主机nginx一般nginx做主机反向代理(网关)有以下配置...

如何用redis实现注册中心

一句话总结使用Redis实现注册中心:服务注册...

爱可可老师24小时热门分享(2020.5.10)

No1.看自己以前写的代码是种什么体验?No2.DooM-chip!国外网友SylvainLefebvre自制的无CPU、无操作码、无指令计数器...No3.我认为CS学位可以更好,如...

Apportable:拯救程序员,IOS一秒变安卓

摘要:还在为了跨平台使用cocos2d-x吗,拯救objc程序员的奇葩来了,ApportableSDK:FreeAndroidsupportforcocos2d-iPhone。App...

JAVA实现超买超卖方案汇总,那个最适合你,一篇文章彻底讲透

以下是几种Java实现超买超卖问题的核心解决方案及代码示例,针对高并发场景下的库存扣减问题:方案一:Redis原子操作+Lua脚本(推荐)//使用Redis+Lua保证原子性publicbo...

3月26日更新 快速施法自动施法可独立设置

2016年3月26日DOTA2有一个79.6MB的更新主要是针对自动施法和快速施法的调整本来内容不多不少朋友都有自动施法和快速施法的困扰英文更新日志一些视觉BUG修复就不翻译了主要翻译自动施...

Redis 是如何提供服务的

在刚刚接触Redis的时候,最想要知道的是一个’setnameJhon’命令到达Redis服务器的时候,它是如何返回’OK’的?里面命令处理的流程如何,具体细节怎么样?你一定有问过自己...

lua _G、_VERSION使用

到这里我们已经把lua基础库中的函数介绍完了,除了函数外基础库中还有两个常量,一个是_G,另一个是_VERSION。_G是基础库本身,指向自己,这个变量很有意思,可以无限引用自己,最后得到的还是自己,...

China&#39;s top diplomat to chair third China-Pacific Island countries foreign ministers&#39; meeting

BEIJING,May21(Xinhua)--ChineseForeignMinisterWangYi,alsoamemberofthePoliticalBureau...

移动工作交流工具Lua推出Insights数据分析产品

Lua是一个适用于各种职业人士的移动交流平台,它在今天推出了一项叫做Insights的全新功能。Insights是一个数据平台,客户可以在上面实时看到员工之间的交流情况,并分析这些情况对公司发展的影响...

Redis 7新武器:用Redis Stack实现向量搜索的极限压测

当传统关系型数据库还在为向量相似度搜索的性能挣扎时,Redis7的RedisStack...

Nginx/OpenResty详解,Nginx Lua编程,重定向与内部子请求

重定向与内部子请求Nginx的rewrite指令不仅可以在Nginx内部的server、location之间进行跳转,还可以进行外部链接的重定向。通过ngx_lua模块的Lua函数除了能实现Nginx...