HikariCP的Postgresql性能问题

时间:2017-03-03 19:35:51

标签: postgresql jdbc hikaricp

我试图将大数据加载到PostgreSQL服务器中的一个表中(总共4​​000万行),小批量(每个csv中有6000行)。我认为HikariCP非常适合这个目的。

这是我使用数据插入获得的吞吐量 Java 8(1.8.0_65),Postgres JDBC驱动程序9.4.1211和HikariCP 2.4.3。

在4分42秒内完成6000行。

我做错了什么以及如何提高插入速度?

关于我的设置的更多信息:

  • 程序在公司网络后面的笔记本电脑中运行。
  • Postgres服务器9.4是带有db.m4.large和50 GB SSD的Amazon RDS。
  • 尚未在表格上创建明确的索引或主键。
  • 程序与大线程池异步插入每一行以保存请求,如下所示:

    private static ExecutorService executorService = new ThreadPoolExecutor(5, 1000, 30L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100000));
    

DataSource配置是:

        private DataSource getDataSource() {
                if (datasource == null) {
                    LOG.info("Establishing dataSource");
                    HikariConfig config = new HikariConfig();
                    config.setJdbcUrl(url);
                    config.setUsername(userName);
                    config.setPassword(password);
                    config.setMaximumPoolSize(600);// M4.large 648 connections tops
                    config.setAutoCommit(true); //I tried autoCommit=false and manually committed every 1000 rows but it only increased 2 minute and half for 6000 rows
                    config.addDataSourceProperty("dataSourceClassName","org.postgresql.ds.PGSimpleDataSource");
                    config.addDataSourceProperty("dataSource.logWriter", new PrintWriter(System.out));
                    config.addDataSourceProperty("cachePrepStmts", "true");
                    config.addDataSourceProperty("prepStmtCacheSize", "1000");
                    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
                    config.setConnectionTimeout(1000);

                    datasource = new HikariDataSource(config);
                }
                return datasource;
            }

这是我阅读源数据的地方:

    private void readMetadata(String inputMetadata, String source) {
            BufferedReader br = null;
            FileReader fr = null;
            try {
                br = new BufferedReader(new FileReader(inputMetadata));
                String sCurrentLine = br.readLine();// skip header;
                if (!sCurrentLine.startsWith("xxx") && !sCurrentLine.startsWith("yyy")) {
                    callAsyncInsert(sCurrentLine, source);
                }
                while ((sCurrentLine = br.readLine()) != null) {
                    callAsyncInsert(sCurrentLine, source);
                }
            } catch (IOException e) {
                LOG.error(ExceptionUtils.getStackTrace(e));
            } finally {
                try {
                    if (br != null)
                        br.close();

                    if (fr != null)
                        fr.close();

                } catch (IOException ex) {
                    LOG.error(ExceptionUtils.getStackTrace(ex));
                }
            }
    }

我是异步插入数据(或尝试使用jdbc!):

            private void callAsyncInsert(final String line, String source) {
                    Future<?> future = executorService.submit(new Runnable() {
                        public void run() {
                            try {
                                dataLoader.insertRow(line, source);
                            } catch (SQLException e) {
                                LOG.error(ExceptionUtils.getStackTrace(e));
                                try {
                                    errorBufferedWriter.write(line);
                                    errorBufferedWriter.newLine();
                                    errorBufferedWriter.flush();
                                } catch (IOException e1) {
                                    LOG.error(ExceptionUtils.getStackTrace(e1));
                                }
                            }
                        }
                    });
                    try {
                        if (future.get() != null) {
                            LOG.info("$$$$$$$$" + future.get().getClass().getName());
                        }
                    } catch (InterruptedException e) {
                        LOG.error(ExceptionUtils.getStackTrace(e));
                    } catch (ExecutionException e) {
                        LOG.error(ExceptionUtils.getStackTrace(e));
                    }
                }

我的DataLoader.insertRow如下:

            public void insertRow(String row, String source) throws SQLException {
                    String[] splits = getRowStrings(row);
                    Connection conn = null;
                    PreparedStatement preparedStatement = null;
                    try {
                        if (splits.length == 15) {
                            String ... = splits[0];
                            //blah blah blah

                            String insertTableSQL = "insert into xyz(...) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
                            conn = getConnection();
                            preparedStatement = conn.prepareStatement(insertTableSQL);
                            preparedStatement.setString(1, column1);
                            //blah blah blah
                            preparedStatement.executeUpdate();
                            counter.incrementAndGet();
                            //if (counter.get() % 1000 == 0) {
                                //conn.commit();
                            //}
                        } else {
                            LOG.error("Invalid row:" + row);
                        }
                    } finally {
                        /*if (conn != null) {
                            conn.close();   //Do preparedStatement.close(); rather connection.close
                        }*/
                        if (preparedStatement != null) {
                            preparedStatement.close();
                        }
                    }
                }

在pgAdmin4中监控时,我注意到了一些事情:

  • 每秒最高交易次数接近50次。
  • 活动数据库会话只有一个,会话总数为15个。
  • 块I / O太多(达到500左右,不确定是否应该关注)

screenshot from pgAdmin

1 个答案:

答案 0 :(得分:2)

您绝对希望使用批处理插入,语句正在外部进行准备,并自动提交。在伪代码中:

PreparedStatement stmt = conn.prepareStatement("insert into xyz(...) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
while ( <data> ) {
   stmt.setString(1, column1);
   //blah blah blah
   stmt.addBatch();
}
stmt.executeBatch();
conn.commit();

即使单个连接上的单个线程也应该能够插入&gt; 5000行/秒。

更新:如果要多线程化,连接数应该是数据库CPU核心数x1.5或2.处理线程数应该匹配,每个处理线程应该处理一个CSV文件使用上面的模式。但是,您可能会发现同一个表中的许多并发插入会在数据库中产生过多的锁争用,在这种情况下,您需要回退处理线程的数量,直到找到最佳并发。

正确大小的池和并发应该很容易达到> 20K行/秒。

另外,请升级到HikariCP v2.6.0。