java - Apache dbcp 连接池无法正常工作

标签 java database-connection apache-commons-dbcp try-with-resources

我正在尝试按照此处的教程使用 apache dbcp2 连接池连接到 mysql 数据库:

https://git-wip-us.apache.org/repos/asf?p=commons-dbcp.git;a=blob;f=doc/PoolingDataSourceExample.java;h=2a12c74898930b9623223db1597b8a8052a6f1df;hb=HEAD

返回连接的我的数据库连接类如下所示:

public class DbConnection {

private static interface Singleton {

    final DbConnection INSTANCE = new DbConnection();
}

private final PoolingDataSource<PoolableConnection> dataSource;

private DbConnection() {
    // A ConnectionFactory that the pool will use to create Connections.
    DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, pass);  //url,user,pass for db connnection

    //implement the pooling functionality.
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxWaitMillis(500);
    config.setMaxTotal(20);
    config.setMaxIdle(5);
    config.setMinIdle(5);
    //PoolingDataSource expect an ObjectPool
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config);
    // Set the poolableConnectionFactory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    this.dataSource = new PoolingDataSource<>(connectionPool);
}

public static Connection getCon() throws SQLException {
    return Singleton.INSTANCE.dataSource.getConnection();
}
} 

我正在使用 apache jmeter 来测试连接并从我的 mysql 数据库返回一些内容。我创建了 100 个用户,启动周期(以秒为单位)为 2 秒。我创建了一个 Http 请求,当我尝试在查看结果树中查看我的响应时,我成功获得了前 20 个请求的响应。从 (21 到 100) 的后续请求有空白响应。我已经解决了许多问题,涉及:

java.sql.SQLException: Cannot get a connection, pool error Timeout waiting for idle object

我访问我的代码:

try (PreparedStatement ps = DbConnection.getCon().prepareStatement("SELECT id FROM test WHERE id =?;")) {
        ps.setString(1, id);
        try (
                ResultSet rs = ps.executeQuery()) {
            return rs.next();
        }
    } catch (Exception ex) {

    }

最佳答案

您没有关闭 Connection 对象,您必须在 try-with-resources block 中声明此类变量:

try (Connection conn = DbConnection.getCon(); 
       PreparedStatement ps = conn.prepareStatement("SELECT id FROM test WHERE id =?;")) {

此外,您还需要关闭ResultSet,可以在方法中调用close方法ResultSet,或者使用a将其添加到try-with-resources block 中返回它的新方法

关于java - Apache dbcp 连接池无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56412903/

相关文章:

java - 从父类访问变量

java - 从 FTPS 服务器检索文件时出现问题

mysql - AWS : Unable to connect Amazon QuickSight to RDS

java - Hibernate C3P0 池机制

java - Spring 2.5 无法获取 JDBC 连接

java - 如何以所需的时间格式获取 Joda Time 中的 Interval 或类似类?

java - FileAppender 打开 FileHandle 但从不记录

c++ - RWDBTBuffer<T>、RWDBVector<T> 和 RWDBDecimalVector 的区别

java - DBCP 池出现错误 : "java.sql.SQLException: Configuration file not found"

java - 打印 Tomcat DBCP DataSource 对象的属性