MySql PreparedStatement executeBatch過慢問題

   在近期工作中,數據庫使用到了MySql引擎,在一次數據導入幾萬條數據,如果一條一條插入,必然性能不佳,顧使用到了JDBC中PreparedStatement的executeBatch方法來批量提交數據,以此提高性能,但結果讓我們大吃一驚,性能不升反降,由於服務器在異地,2萬條左右的數據,整整提交了20分鐘,簡直破我的三觀,於是就開啓了排查之路。

   過程中一直懷疑代碼有問題,線程死鎖(用到了多線程提交數據),數據庫事務過長等等問題,後面才發現rewriteBatchedStatements參數未開啓,開啓參數後,均值8秒提交完成,最優值可以到5秒(與網絡有關),最高值10秒。

    到底爲什麼這個參數會產生這麼大的性能差距?於是引起了我對這個參數的一攤究竟。

   開始書寫最簡單的測試代碼,環境如下:

    OS:MAC 8G內存 256GSSD

    MySql server:本機,version:5.7.11

   JDBC 驅動:5.1.31

   數據量:總共提交100萬條數據

   數據列:單列

   執行sql如下:

insert into t_student(name) values(?)

   測試程序如下:

public static void main(String[] args){
        String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&rewriteBatchedStatements=true&useServerPrepStmts=true";
        int batchSize = 0;
        Long l = System.currentTimeMillis();
        executeBatch(url,(batchSize<=0 || batchSize > 60000) ? 60000 : batchSize);
        System.out.println("useServerPrepStmts and rewriteBatchedStatements time:"+(System.currentTimeMillis()-l)+"ms");

        url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&rewriteBatchedStatements=true";
        l = System.currentTimeMillis();
        executeBatch(url,batchSize);
        System.out.println(" rewriteBatchedStatements time:"+(System.currentTimeMillis()-l)+"ms");

        url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true";
        l = System.currentTimeMillis();
        executeBatch(url,batchSize);
        System.out.println("  time:"+(System.currentTimeMillis()-l)+"ms");
    }

    public static void executeBatch(String url,int batchSize){
        Connection connection = null;
        try {
            String sql = "insert into t_student(name) values(?)";
            connection = getConnection(url);
            connection.setAutoCommit(false);
            PreparedStatement pstm = connection.prepareStatement(sql);
            for(int  i = 0 ; i < 1000000 ; i++){
                pstm.setString(1,"li.guohui"+i);
                pstm.addBatch();
                if(batchSize > 0) {
                    if (i % batchSize == 0) {
                        pstm.executeBatch();
                    }
                }
            }
            pstm.executeBatch();
            connection.commit();
        }catch (Exception e){
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            close(connection);
        }

    }

    public static Connection getConnection(String url) throws ClassNotFoundException, SQLException {
        String username = "root";
        String password = "root";
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(url,username,password);
    }

    public static void close(Connection connection){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

執行結果如下:



useServerPrepStmts and rewriteBatchedStatements time:  8506ms
rewriteBatchedStatements time:                         5213ms
mysql time:                                            161732ms

從結果一看,一目瞭然,url中僅開啓參數rewriteBatchedStatements時,性能最佳,5秒多些就能處理結束;

WHY??????

通過tcpdump網絡抓包,指令格式(sudo tcpdump -i 10 -vv -nn port 3306 -X詳細說明請看博客,我們可以看到三個參數的不同處理方式:

1、同時開啓useServerPrepStmts and rewriteBatchedStatements:


mysql的jdbc連接器採用預處理的方式提交數據,將預處理數據線發送到數據庫服務器,然後再發送一個一個的參數數據,一個操作需要發送兩次。

2、僅開啓rewriteBatchedStatements參數,抓包結果如下:


mysql的jdbc連接器將需要插入的值拼接在插入語句中,多值一次發送:“insert into table(colName) values('a'),('b').....”形式;這樣數據只需要一次提交數據到數據庫服務器;

3、未開啓useServerPrepStmts and rewriteBatchedStatements參數,抓包結果如下:


從抓包結果,可以看出,mysql的jdbc連接器,將100萬條數分100萬次提交到數據庫服務器,這可想而知,這是多麼的慢,不僅僅數據提交,tcp連接等等等都會消耗一定時間。


至此,我們大概明白了爲什麼executeBatch如此慢的原因,總結如下:

a、開啓rewriteBatchedStatements而未開啓useServerPrepStmts參數,mysql連接器以字符數值拼接多值sql,一次發送到數據庫服務器;

b、同時rewriteBatchedStatements和useServerPrepStmts參數,MySQL連接器以預編譯的方式將sql和值分開發送,這種方式需要注意佔位符過多的情況,一次MySQL最多的佔位符爲65535個,即每次執行executeBatch時,數據個數不能超過65535個(與數據條數、提交的表字段個數有關),否則會出現以下錯誤:

java.sql.SQLException: Prepared statement contains too many placeholders
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1094)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
	at com.mysql.jdbc.ServerPreparedStatement.serverPrepare(ServerPreparedStatement.java:1623)
	at com.mysql.jdbc.ServerPreparedStatement.<init>(ServerPreparedStatement.java:402)
	at com.mysql.jdbc.ServerPreparedStatement.prepareBatchedInsertSQL(ServerPreparedStatement.java:3037)
	at com.mysql.jdbc.PreparedStatement.executeBatchedInserts(PreparedStatement.java:1665)
	at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1377)

c、什麼都不開啓,MySQL連接器默認一條一條提交數據,多次與數據庫服務器交互。

**&&性能比較(在多條數據提交時): 開啓rewriteBatchedStatements  > 同時開啓rewriteBatchedStatements和useServerPrepStmts > 未開啓


接下來,我們再來看看rewriteBatchedStatements參數的源碼處理過程:

addBatch方法都做了啥?

往批處理維護的緩存數組中加入需要插入數據庫的值:


執行executeBatch方法時,就開始將batchedArgs裏的數據通過連接socket tcp方式發送到數據庫服務器:


但是從源碼中注意到,如果一次提交的數據少於3條,那麼批量提交是不生效的,該連接器生效是從4.1.0版本以上支持。


MySQL其它連接器參數說明:

請看官方文檔:https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html




     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章