Apache dbcp 连接池无法正常工作

Apache dbcp connection pooling not working properly

我正在尝试使用 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

我的数据库连接 class return 连接看起来像这样:

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 来测试连接和 return 来自我的 mysql 数据库的东西。我创建了 100 个用户,启动时间(以秒为单位)为 2 秒。我创建了一个 Http request,当我试图在 view results tree 中查看我的响应时,我成功地获得了前 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 块中声明此类变量:

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

您还需要关闭 ResultSet,在方法中调用 close 方法 ResultSet 或使用返回它的新方法将其添加到 try-with-resources 块