首页 > 编程语言 >java加快批量插入的两个方法

java加快批量插入的两个方法

时间:2023-02-10 17:23:16浏览次数:42  
标签:java 批量 rewriteBatchedStatements 插入 eiDeviceStates executor true

一:配置参数:

关于rewriteBatchedStatements这个参数介绍:

MySQL的JDBC连接的url中要加rewriteBatchedStatements参数,并保证5.1.13以上版本的驱动,才能实现高性能的批量插入。
MySQL JDBC驱动在默认情况下会无视executeBatch()语句,把我们期望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,批量插入实际上是单条插入,直接造成较低的性能。
只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL
另外这个选项对INSERT/UPDATE/DELETE都有效

添加rewriteBatchedStatements=true这个参数后的执行速度比较:
同个表插入一万条数据时间近似值:
JDBC BATCH 1.1秒左右 > Mybatis BATCH 2.2秒左右 > 拼接SQL 4.5秒左右

jdbc-url: jdbc:mysql://${MYSQL_HOST:xxx}:${MYSQL_PORT:3306}/${MYSQL_DB:xxx}?
useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true&rewriteBatchedStatements=true

二:多线程插入

1、引入多线程配置类

@Configuration
public class ThreadConfig implements AsyncConfigurer {



    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(16);
        executor.setMaxPoolSize(1000);
        executor.setQueueCapacity(500);
        //线程前缀
        executor.setThreadNamePrefix("executor-");
        executor.setKeepAliveSeconds(30000);
        executor.initialize();
        return executor;
    }
}

2、实际调用引用

@Slf4j
@Service
public class CreateDataJob {

    @Autowired
    private SequenceGen sequenceGen;


    @Autowired
    private ThreadConfig executorService;


    /**
     * 模拟数据
     *
     * @Auth fxr
     * @Date 2021年2月10日13:26:18
     */
    @Scheduled(cron = "0 0/15 * * * ?")
    @Transactional
    public void createData() {
        //mysql
        QueryWrapper<DeviceStateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 1);
        List<DeviceStateEntity> eiDeviceStates = deviceStateService.list(queryWrapper);
        eiDeviceStates.parallelStream().forEach(e -> {
            e.setOccurredTime(new Date());
            e.setId(sequenceGen.gen());
        });
        deviceStateService.remove(queryWrapper);
        //多线程入库
        CountDownLatch countDownLatch = null;
        int count = eiDeviceStates.size() / 4;
        List<DeviceStateEntity> newlist = null;
        //分4个线程执行
        for (int i = 0; i < 4; i++) {
            int startIndex = (i * count);
            int endIndex = (i + 1) * count;
            if (i == 3) {
                endIndex = eiDeviceStates.size();
            }
            newlist = eiDeviceStates.subList(startIndex, endIndex);
            List<DeviceStateEntity> finalNewlist = newlist;
            executorService.getAsyncExecutor().execute(() -> {
                try {
                    //调用数据库实现插入
                    deviceStateService.saveBatch(finalNewlist);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

    }

}

  

标签:java,批量,rewriteBatchedStatements,插入,eiDeviceStates,executor,true
From: https://www.cnblogs.com/innocenter/p/17109731.html

相关文章

  • JAVA8之Stream(其一:分页)
    分页,是项目开发中的常驻者,想必大家都使用过PageHelper进行分页,或者利用mysql语句的limit进行分页。利用PageHelper去分页,无非就是在你的sql语句外层嵌套一个limit,一旦遇到......
  • Go使用协程批量获取数据,加快接口返回速度
    服务端经常需要返回一个列表,里面包含很多用户数据,常规做法当然是遍历然后读缓存。使用Go语言后,可以并发获取,极大提升效率。使用channelpackagemainimport("fmt"......
  • JavaScript 获取元素的 坐标位置
         https://blog.csdn.net/im20166456/article/details/113793437?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefaul......
  • JavaScript中的函数
    函数:一个被设计为执行特定任务的代码块语法通过function关键词定义,后面跟着其函数名称,然后是一对圆括号,圆括号中可以定义一些函数的参数。没有名称的函数呢?函数名称......
  • Java读取上传的word文档内容
    @RequestMapping(value="save",method=RequestMethod.POST)publicRsave(@RequestParam("imgFile")MultipartFilefile){StringfileName=file.getOrigin......
  • Java连接redis的工具类
    importorg.springframework.data.redis.core.StringRedisTemplate;importorg.springframework.stereotype.Component;importjavax.annotation.Resource;importjav......
  • oasys系统_JAVA代码审计
    oasys系统_JAVA代码审计一、前言oasys是一个OA办公自动化系统,使用Maven进行项目管理,基于springboot框架开发的项目。可以看到该项目的资源文件中是mappers且pom.xml里有M......
  • java 存在连续三个奇数的数组
    说明给你一个整数数组arr,请你判断数组中是否存在连续三个元素都是奇数的情况:如果存在,请返回true;否则,返回false。 代码 publicbooleanthreeConsecutiveOdds(......
  • 浏览器中的JavaScript(2)
    2.2注册事件处理程序摘要:有两种事件处理程序的方式。第一种是web早期就有的,及设置作为事件的对象或文档元素的一个属性。第二种方法是把处理程序传给这个元素或对象或元......
  • 项目搭建碰到java.lang.NoClassDefFoundError
    基本都是pom依赖包冲突导致的,可以这样来解决:找到pom.xml找到依赖项   一般ClassNotfound会给一个具体的类名。搜索这个类名,看是在那个pom里面。然后在pom依赖项......