HikariCP没有关闭close()上的连接(连接泄漏)

时间:2019-05-26 11:35:44

标签: java postgresql database-connection datasource hikaricp

我正在使用HikariCP 3.3.1和PostgreSQL。但是我在关闭连接时遇到问题,在Hikari配置中,我将最大池大小设置为15,将最小空闲连接设置为5,但是在处理数据库几分钟后,我发现连接没有关闭,它们会堆叠越来越多(现在几乎有100个空闲连接)。 enter image description here

我的连接器类:

Connector.java

public class Connector implements IConnector {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;

static {
    config.setDriverClassName(org.postgresql.Driver.class.getName());
    config.setJdbcUrl("jdbc:postgresql://localhost:5432/vskDB");
    config.setUsername("postgres");
    config.setPassword("root");
    config.setMinimumIdle(5);
    config.setMaximumPoolSize(15);
    config.setConnectionTimeout(20000);
    config.setIdleTimeout(300000);
    ds = new HikariDataSource(config);
}

public Connection getConnection() {
    log.info("getConnection() invoked");
    try {
        return ds.getConnection();
    } catch (SQLException e) {
        log.error("Can't get connection from DataSource.");
        log.error(e.getMessage());
        System.out.println(e.getMessage());
    }
    return null;
}

Connector() {
}
}

这是我的DAO类(简体): UserDAO.java

public class UserDatabaseDAO implements UserDAO {
    private Connector connector = new Connector();
    private Connection dbConnection;

    @Override
    public void removeUser(Long id) {
        try {
            dbConnection = connector.getConnection();
            if (dbConnection == null)
                throw new ConnectException();

            PreparedStatement preparedStatement = dbConnection.prepareStatement("DELETE FROM users WHERE user_id = ?");
            preparedStatement.setLong(1, id);
            preparedStatement.execute();

        } catch (SQLException | ConnectException e) {
            log.error("Can't remove user from database");
            log.error(e.getMessage());
            System.out.print(e.getMessage());
        } finally {
            try {
                dbConnection.close();
            } catch (SQLException e) {
                log.error("Can't close connection");
                log.error(e.getMessage());
                System.out.print(e.getMessage());
            }
        }
    }
}

Here我发现了有关Hikari的一些事实问题:
您必须在HikariCP给您的连接实例上调用close()

也许我的dbConnection.close()不能用,因为它只是Hikari用getConnection()方法给我的Connection的副本。

1 个答案:

答案 0 :(得分:2)

您忘记也关闭PreparedStatement

BigDecimal idhabitacion = new BigDecimal(request.getParameter("idhabitacion"));
  

立即释放此Statement对象的数据库和JDBC资源,而不是等待它自动关闭时发生。通常最好的做法是在完成使用资源后立即释放资源,以避免占用数据库资源。

相关问题