使用iBatis插入数据速度的测试

性能测试时遇到一个问题,独立的线程只负责数据入库,但测试发现数据入库速度比产生的慢,导致数据堆积,虚拟机内存使用完,于是做一个测试,看看到底入库的速度有多快。

测试关键代码:
private static void executeBatch() throws SQLException
{
    long beginTime = System.currentTimeMillis();
    sqlMapClient.startBatch();
    for (ActiveRecord activeRecord : activeRecordList)
    {
        sqlMapClient.insert("insert", activeRecord);
    }
    sqlMapClient.executeBatch();
    System.out.printf("%d records:executeBatch finished in %d milliseconds from the begining\r\n", activeRecordList.size(), System.currentTimeMillis() - beginTime);
}

private static void execute() throws SQLException
{
    long beginTime = System.currentTimeMillis();
    for (ActiveRecord activeRecord : activeRecordList)
    {
        sqlMapClient.insert("insert", activeRecord);
    }
    System.out.printf("%d records:execute finished in %d milliseconds from the begining\r\n", activeRecordList.size(), System.currentTimeMillis() - beginTime);
}


测试结果:
# java -classpath ./:ibatis/ibatis-2.3.4.726.jar:ibatis/ojdbc5.jar ibatis.ActiveRecordTest
1 records:execute finished in 30 milliseconds from the begining
1 records:executeBatch finished in 12 milliseconds from the begining
10 records:execute finished in 108 milliseconds from the begining
10 records:executeBatch finished in 111 milliseconds from the begining
100 records:execute finished in 935 milliseconds from the begining
100 records:executeBatch finished in 1184 milliseconds from the begining
1000 records:execute finished in 9695 milliseconds from the begining
1000 records:executeBatch finished in 9344 milliseconds from the begining
10000 records:execute finished in 95788 milliseconds from the begining
10000 records:executeBatch finished in 82613 milliseconds from the begining

结果分析:
从10000条记录插入耗时82613ms计算,大约每秒钟可入库120条记录,因为这个测试代码只做了这一件事,所以正式业务代码的效率还会比这个低,我们遇到的问题刚好是用户行为轨迹的业务,业务要求的TPS是90,相当于每秒钟最少产生90条记录,加上业务代码的逻辑,已经比较接近iBatis入库速度的上限。
建议:
如果入库的数据量接近或超过iBatis的上限,可以考虑将数据分批,多个线程占用单独的数据库连接进行入库。

你可能感兴趣的:(性能,ibatis,批量查询)