java - Apache Tomcat JDBC 连接池在批处理\批量插入时性能不佳

标签 java tomcat jdbc bulkinsert jdbc-pool

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

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

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

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

在使用连接池之前,我使用 com.mysql.jdbc.jdbc2.optional.MysqlDataSource 作为我的数据源。使用以下行配置连接:

dataSource.setRewriteBatchedStatements(true);

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

最佳答案

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

关于java - Apache Tomcat JDBC 连接池在批处理\批量插入时性能不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32848380/

相关文章:

java - Spring Web服务抛出异常

java - 如何在 Java 中的 Switch Case 中调用多个方法

java - 如何显示来自社交媒体的推特或动态数据......?

java - SSL : CSR file created with openSSL and installing with keytool

hibernate - Tomcat 上的 Spring Security/JSF/Hibernate 意外 session 劫持?

Java 数据层次结构和行映射

java - 如何使用存储过程进行选择

java - 通过java将问题插入数据库

JavaFX淡出阶段并关闭

java - 修改 SlidingTabStrip 中的 Indicator 颜色