【问题标题】:Apache dbcp connection pooling not working properlyApache dbcp 连接池无法正常工作
【发布时间】:2019-10-18 03:43:33
【问题描述】:

我正在尝试按照此处的教程使用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 request,当我尝试在view results tree 中查看我的回复时,我成功获得了前20 个请求的回复。 (21 到 100) 的后续请求有空白响应。我经历了许多涉及的问题:

java.sql.SQLException:无法获取连接,池错误超时 等待空闲对象

我以如下方式访问我的代码:

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) {

    }

【问题讨论】:

  • 你能显示使用getCon()的代码吗?可能是使用后没有关闭接收到的连接造成的
  • @user7294900 我添加了我如何访问我的代码

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


【解决方案1】:

你没有关闭 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 块中

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 2014-01-09
    • 2013-01-06
    • 2019-12-02
    • 2019-03-03
    • 2020-11-14
    • 2013-06-09
    • 2016-12-01
    相关资源
    最近更新 更多