數(shù)據(jù)庫(kù)批量數(shù)據(jù)插入

為了測(cè)試分布式定時(shí)任務(wù)的性能篮赢,以處理數(shù)據(jù)庫(kù)數(shù)據(jù)為基礎(chǔ)測(cè)試币砂,所以需要在數(shù)據(jù)庫(kù)里初始化一個(gè)表建峭,大概是200w條數(shù)據(jù)。
1决摧、因?yàn)槭且粋€(gè)SpringBoot服務(wù)亿蒸,spring提供的JdbcTemplate有批量插入的功能,所以自然想到直接用它蜜徽,代碼是這個(gè)樣子:

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("---------初始化數(shù)據(jù)完畢祝懂,耗時(shí):"+(endTime-beginTime)+"ms----------");
   // System.exit(0);
}

但是結(jié)果確出人意料,平均耗時(shí)大概是372817ms/1w條拘鞋,簡(jiǎn)直可怕砚蓬,想到時(shí)間可能會(huì)長(zhǎng),但是沒想到這么長(zhǎng)盆色,查了資料說(shuō)要開啟批量插入支持灰蛙,debug了下確實(shí)走的批量插入祟剔,不明白,應(yīng)該是哪里出了問(wèn)題摩梧,畢竟這么成熟的框架物延,性能不至于這么差,之后會(huì)分析原因仅父。

2叛薯、用框架不行,那就用最原始的JDBC操作了笙纤,直接用java.sql中的批量操作耗溜,代碼是這個(gè)樣子的:

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("---------初始化數(shù)據(jù)完畢,耗時(shí):"+(end-begin)+"ms----------");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
        }
    }

耗時(shí)2643ms/1w條省容,看著比之前快很多抖拴,但還是不夠快,進(jìn)入源碼看看腥椒,雖然用的是Java自帶的阿宅,算是往下了一層,但是這樣的批量底層實(shí)現(xiàn)還是一條一條執(zhí)行:

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這里的時(shí)候發(fā)現(xiàn)了極其詭異的事笼蛛,1和2都是走的上面這段代碼洒放,但是1慢了太多,不明白為啥伐弹。

debug時(shí)發(fā)現(xiàn)這么一段:

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);     //默認(rèn)執(zhí)行的是這一步  //***************************
                return var3;
            }

1和2默認(rèn)都是走的executeBatchSerially這個(gè)方法拉馋,里面就是上一段代碼那樣一條一條遍歷執(zhí)行sql(不明白為啥時(shí)間差那么多)。那executeBatchedInserts呢惨好?進(jìn)入看一下:

          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;
                        }

                      //會(huì)循環(huán)執(zhí)行這一步將參數(shù)值拼到一起
                        batchedParamIndex = this.setOneBatchedParameterSet(batchedStatement, batchedParamIndex, this.batchedArgs.get(batchCounter++));
                    }

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

在數(shù)據(jù)庫(kù)連接串中加入rewriteBatchedStatements=true(感覺這樣才是真正的batch處理)

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

debug看executeBatchedInserts方法中上面一段執(zhí)行后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())
... ...

果然這樣確實(shí)批量處理了煌茴,耗時(shí)1405ms/1w條(開啟了rewriteBatchedStatements后1和2時(shí)間差不多都是這么多)。

3日川、2中開啟批量處理后可以看到就是相當(dāng)于拼成了一條sql蔓腐,那直接自己拼就可以省去框架的其他處理操作,是不是會(huì)快點(diǎn)龄句?再試試最原始的一條sql回论,直接拼接成一條sql,代碼是這個(gè)樣子的:

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++) {        //這里分批是因?yàn)镸ysql有大小限制分歇,sql不能拼太長(zhǎng)
            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("---------初始化數(shù)據(jù)完畢傀蓉,耗時(shí):"+(end-begin)+"ms----------");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
        }
    }

耗時(shí)266ms/1w條,這個(gè)時(shí)間似乎可以接受职抡。但是有沒有更快的呢葬燎?畢竟現(xiàn)在還是停留在調(diào)用API,存儲(chǔ)過(guò)程?還有其他谱净?后續(xù)....

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末窑邦,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子壕探,更是在濱河造成了極大的恐慌冈钦,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件李请,死亡現(xiàn)場(chǎng)離奇詭異瞧筛,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)捻艳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門驾窟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)庆猫,“玉大人认轨,你說(shuō)我怎么就攤上這事≡屡啵” “怎么了嘁字?”我有些...
    開封第一講書人閱讀 162,764評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)杉畜。 經(jīng)常有香客問(wèn)我纪蜒,道長(zhǎng),這世上最難降的妖魔是什么此叠? 我笑而不...
    開封第一講書人閱讀 58,193評(píng)論 1 292
  • 正文 為了忘掉前任纯续,我火速辦了婚禮,結(jié)果婚禮上灭袁,老公的妹妹穿的比我還像新娘猬错。我一直安慰自己,他們只是感情好茸歧,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評(píng)論 6 388
  • 文/花漫 我一把揭開白布倦炒。 她就那樣靜靜地躺著,像睡著了一般软瞎。 火紅的嫁衣襯著肌膚如雪逢唤。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,182評(píng)論 1 299
  • 那天涤浇,我揣著相機(jī)與錄音鳖藕,去河邊找鬼。 笑死只锭,一個(gè)胖子當(dāng)著我的面吹牛著恩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼页滚,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼召边!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起裹驰,我...
    開封第一講書人閱讀 38,917評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤隧熙,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后幻林,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贞盯,經(jīng)...
    沈念sama閱讀 45,329評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評(píng)論 2 332
  • 正文 我和宋清朗相戀三年沪饺,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了躏敢。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,722評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡整葡,死狀恐怖件余,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情遭居,我是刑警寧澤啼器,帶...
    沈念sama閱讀 35,425評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站俱萍,受9級(jí)特大地震影響端壳,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜枪蘑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評(píng)論 3 326
  • 文/蒙蒙 一损谦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧岳颇,春花似錦照捡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至掂摔,卻和暖如春术羔,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背乙漓。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工级历, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人叭披。 一個(gè)月前我還...
    沈念sama閱讀 47,729評(píng)論 2 368
  • 正文 我出身青樓寥殖,卻偏偏與公主長(zhǎng)得像玩讳,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子嚼贡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容