3

我最近将 Apache Tomcat JDBC 连接池合并到我的应用程序中(使用 MySQL DB)。我之前尝试过使用 Apache DBCP,但不喜欢它的结果,而且即使我运行独立的 java 应用程序并且根本不使用 tomcat,tomcat 的实现似乎也符合我的需求。

最近,我在执行批量(又名 bulk )插入查询时遇到了一个巨大的性能问题。

我有一个流程,其中我以批处理方式将 ~2500 条记录插入到表中。使用 jdbc 连接池需要很长时间,而恢复为每个查询打开连接时需要几秒钟(无池)。

我编写了一个小型应用程序,将 30 行插入到同一个表中。池化时需要 12 秒,不池化时大约需要 800 毫秒。

在使用连接池之前,我将com.mysql.jdbc.jdbc2.optional.MysqlDataSource其用作我的 DataSource。使用以下行配置了连接:

dataSource.setRewriteBatchedStatements(true);

我很确定这是两种方法之间的核心区别,但在 jdbc-pool 中找不到等效参数。

4

1 回答 1

4

MySql JDBC 驱动不支持批量操作。RewriteBatchedStatement 是你能得到的最好的。这里是来自 mysql PreparedStatement.java的代码:

 try {
            statementBegins();

            clearWarnings();

            if (!this.batchHasPlainStatements && this.connection.getRewriteBatchedStatements()) {

                if (canRewriteAsMultiValueInsertAtSqlLevel()) {
                    return executeBatchedInserts(batchTimeout);
                }

                if (this.connection.versionMeetsMinimum(4, 1, 0) && !this.batchHasPlainStatements && this.batchedArgs != null
                        && this.batchedArgs.size() > 3 /* cost of option setting rt-wise */) {
                    return executePreparedBatchAsMultiStatement(batchTimeout);
                }
            }

            return executeBatchSerially(batchTimeout);
        } finally {
            this.statementExecuting.set(false);

            clearBatch();
        }

这也是我不喜欢 MySql 而更喜欢 Postgres 的原因之一

编辑:

您应该结合连接池、批处理操作和 RewriteBatchedStatement 选项。您可以通过 jdbc url 参数设置 RewriteBatchedStatement 选项:jdbc:mysql://localhost:3307/mydb?rewriteBatchedStatements=true

于 2015-09-29T17:11:27.123 回答