数据库批量数据插入

为了测试分布式定时任务的性能,以处理数据库数据为基础测试,所以需要在数据库里初始化一个表,大概是200w条数据。
1、因为是一个SpringBoot服务,spring提供的JdbcTemplate有批量插入的功能,所以自然想到直接用它,代码是这个样子:

private void initialDatabase() {
    long beginTime = new Date().getTime();
    final int total = 2*1000000;
    jdbcTemplate.batchUpdate(initialDatabaseSql, new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
            preparedStatement.setString(1,String.valueOf(i));
            preparedStatement.setString(2,"data for test timerTask");
        }
        public int getBatchSize() {
            return total;
        }
    });
    long endTime = new Date().getTime();
    System.out.println("---------初始化数据完毕,耗时:"+(endTime-beginTime)+"ms----------");
   // System.exit(0);
}

但是结果确出人意料,平均耗时大概是372817ms/1w条,简直可怕,想到时间可能会长,但是没想到这么长,查了资料说要开启批量插入支持,debug了下确实走的批量插入,不明白,应该是哪里出了问题,毕竟这么成熟的框架,性能不至于这么差,之后会分析原因。

2、用框架不行,那就用最原始的JDBC操作了,直接用java.sql中的批量操作,代码是这个样子的:

private void initialDatabaseNewest() {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/timer?useUnicode=true&characterEncoding=utf-8","root","123456");
        connection.setAutoCommit(false);
        String sql = "insert into message(id,message,createTime) values(?,?,SYSDATE()) ";
        statement = connection.prepareStatement(sql);
        long begin = System.currentTimeMillis();
        int i =0,j=1;
        for (;j<100;j++) {
            for (; i < 10000*j; i++) {
                statement.setString(1,String.valueOf(i));
                statement.setString(2,"data for test timerTask");
                statement.addBatch();
            }
            statement.executeBatch();
        }
        connection.commit();
        long end = System.currentTimeMillis();
        System.out.println("---------初始化数据完毕,耗时:"+(end-begin)+"ms----------");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
        }
    }

耗时2643ms/1w条,看着比之前快很多,但还是不够快,进入源码看看,虽然用的是Java自带的,算是往下了一层,但是这样的批量底层实现还是一条一条执行:

for(this.batchCommandIndex = 0; this.batchCommandIndex < nbrCommands; ++this.batchCommandIndex) {
                        Object arg = this.batchedArgs.get(this.batchCommandIndex);

                        try {
                            if (!(arg instanceof String)) {
                                PreparedStatement.BatchParams paramArg = (PreparedStatement.BatchParams)arg;
                                updateCounts[this.batchCommandIndex] = this.executeUpdateInternal(paramArg.parameterStrings, paramArg.parameterStreams, paramArg.isStream, paramArg.streamLengths, paramArg.isNull, true);
                                this.getBatchedGeneratedKeys(this.containsOnDuplicateKeyUpdateInSQL() ? 1 : 0);
                            } else {
                                updateCounts[this.batchCommandIndex] = this.executeUpdateInternal((String)arg, true, this.retrieveGeneratedKeys);
                                this.getBatchedGeneratedKeys(this.results.getFirstCharOfQuery() == 'I' && this.containsOnDuplicateKeyInString((String)arg) ? 1 : 0);
                            }
                        }
    }

debug这里的时候发现了极其诡异的事,1和2都是走的上面这段代码,但是1慢了太多,不明白为啥。

debug时发现这么一段:

try {
                this.statementBegins();
                this.clearWarnings();
                long[] var3;
                if (!this.batchHasPlainStatements && this.connection.getRewriteBatchedStatements()) {
                    if (this.canRewriteAsMultiValueInsertAtSqlLevel()) {
                        var3 = this.executeBatchedInserts(batchTimeout);        //***************************
                        return var3;
                    }

                    if (this.connection.versionMeetsMinimum(4, 1, 0) && !this.batchHasPlainStatements && this.batchedArgs != null && this.batchedArgs.size() > 3) {
                        var3 = this.executePreparedBatchAsMultiStatement(batchTimeout);  //***************************
                        return var3;
                    }
                }

                var3 = this.executeBatchSerially(batchTimeout);     //默认执行的是这一步  //***************************
                return var3;
            }

1和2默认都是走的executeBatchSerially这个方法,里面就是上一段代码那样一条一条遍历执行sql(不明白为啥时间差那么多)。那executeBatchedInserts呢?进入看一下:

          for(int i = 0; i < ex; ++i) {
                        if (i != 0 && i % numValuesPerBatch == 0) {
                            try {
                                updateCountRunningTotal += batchedStatement.executeLargeUpdate();
                            } catch (SQLException var49) {
                                sqlEx = this.handleExceptionForBatch(batchCounter - 1, numValuesPerBatch, updateCounts, var49);
                            }

                            this.getBatchedGeneratedKeys(batchedStatement);
                            batchedStatement.clearParameters();
                            batchedParamIndex = 1;
                        }

                      //会循环执行这一步将参数值拼到一起
                        batchedParamIndex = this.setOneBatchedParameterSet(batchedStatement, batchedParamIndex, this.batchedArgs.get(batchCounter++));
                    }

                    try {
                        updateCountRunningTotal += batchedStatement.executeLargeUpdate();
                    } 

在数据库连接串中加入rewriteBatchedStatements=true(感觉这样才是真正的batch处理)

 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/timer?useUnicode=true&rewriteBatchedStatements=true"

debug看executeBatchedInserts方法中上面一段执行后PreparedStatement中的sql是这样的:

com.mysql.jdbc.PreparedStatement@3098eb37: insert into message(id,message,createTime) 
values('0','data for test timerTask',SYSDATE()) 
,('1','data for test timerTask',SYSDATE())
,('2','data for test timerTask',SYSDATE())
,('3','data for test timerTask',SYSDATE())
,('4','data for test timerTask',SYSDATE())
,('5','data for test timerTask',SYSDATE())
... ...

果然这样确实批量处理了,耗时1405ms/1w条(开启了rewriteBatchedStatements后1和2时间差不多都是这么多)。

3、2中开启批量处理后可以看到就是相当于拼成了一条sql,那直接自己拼就可以省去框架的其他处理操作,是不是会快点?再试试最原始的一条sql,直接拼接成一条sql,代码是这个样子的:

private void initialDatabaseNew() {
    Connection connection = null;
    Statement statement = null;
    try {
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/timer?useUnicode=true&characterEncoding=utf-8","root","123456");
        connection.setAutoCommit(false);
        statement = connection.createStatement();

        long begin = System.currentTimeMillis();
        int i =0,j=1;
        for (;j<101;j++) {        //这里分批是因为Mysql有大小限制,sql不能拼太长
            StringBuffer sql = new StringBuffer("insert into message(id,message,createTime) values");
            for (; i < 20000*j; i++) {
                sql.append("('" + i + "','data for test timerTask',SYSDATE()),");
            }
            sql.append("('" + i++ + "','data for test timerTask',SYSDATE())");
            statement.execute(sql.toString());
        }
        connection.commit();
        long end = System.currentTimeMillis();
        System.out.println("---------初始化数据完毕,耗时:"+(end-begin)+"ms----------");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
        }
    }

耗时266ms/1w条,这个时间似乎可以接受。但是有没有更快的呢?毕竟现在还是停留在调用API,存储过程?还有其他?后续....

你可能感兴趣的:(数据库批量数据插入)