java - HikariPool 达到最大连接数

标签 java sqlite jdbc hikaricp connection-leaks

我正在使用 HikariCP 运行 SQLite 数据库。 我的配置如下所示:

public class SQLiteDataSource {
    private static final HikariConfig config = new HikariConfig();
    private static final HikariDataSource ds;

    static {


        config.setJdbcUrl("jdbc:sqlite:database.db");
        config.setConnectionTestQuery("SELECT 1");
        config.addDataSourceProperty("cachePrepStmts", true);
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSwlLimit", "2048");
        config.setIdleTimeout(10000);
        config.setMaxLifetime(30000);
        config.setValidationTimeout(30000);
        config.setMaximumPoolSize(100);
        config.setMinimumIdle(10);
        config.setAllowPoolSuspension(false);

        ds = new HikariDataSource(config);
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}

方法getConnection()用于从数据库的表中获取数据。 这些函数如下所示:

// This is a slightly abreviated function to get a boolean from a table in the database where the primary key "id" matches the one requested

 public static Boolean getBoolean(String Id, String column) {
        try (final PreparedStatement preparedStatement = SQLiteDataSource.getConnection()
                // language=SQLite
                .prepareStatement("SELECT " + column + " FROM table WHERE id = ?")) {

            preparedStatement.setString(1, Id);

            try (final ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    Boolean bool = resultSet.getBoolean(setting);
                    resultSet.close();
                    preparedStatement.getConnection().close();
                    return bool;
                }
            }

            preparedStatement.getConnection().close();

        } catch (SQLException e) {
        e.printStackTrace();
        }
        return false;
    }

每次调用该函数时,PreparedStatement 的连接都会在最后关闭。 然而,池大小不断增长,直到达到最大池大小并超时。

有什么方法可以阻止这种情况或强制关闭连接吗?

最佳答案

按照 @Nithin 建议删除 preparedStatement.getConnection().close() ,并在 try-with-resources block 中显式获取连接:

try (Connection con = SQLiteDataSource.getConnection();final PreparedStatement preparedStatement = con
                // language=SQLite
                .prepareStatement("SELECT " + column + " FROM table WHERE id = ?")) {

这样连接也会在 block 结束时关闭

关于java - HikariPool 达到最大连接数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61169841/

相关文章:

javascript - 使用 SQLite3 在 Node js 中为 GET 查询准备语句

java - Java 中 MySQL 插入语句的性能 : Batch mode prepared statements vs single insert with multiple values

java - 无法从外部 IPV4 地址连接到 MySQL 服务器

java - 添加模块描述符时没有名为 'entityManagerFactory' 的 bean 可用

java - 使用浏览器打开 URLs - RoboVM/iOS

c++ - Sqlite:如何从 C++ 绑定(bind)和插入日期?

java - 使用 Spring JDBC 的简单交易?

java - Wicket 与主要方法(Wicket 如何工作?)

java - 如何编辑可更改的图标比例?

android - 整个应用程序生命周期中的 getWritableDatabase() 实例