我正在嘗試按照此處的教程mysql使用連接池連接到數(shù)據(jù)庫:apache dbcp2https://git-wip-us.apache.org/repos/asf?p=commons-dbcp.git;a=blob;f=doc/PoolingDataSourceExample.java;h=2a12c74898930b9623223db1597b8a8052a6f1df;hb=HEAD返回連接的我的數(shù)據(jù)庫連接類如下所示: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 數(shù)據(jù)庫返回一些東西。我創(chuàng)建了 100 個用戶,啟動時間(以秒為單位)為 2 秒。我創(chuàng)建了一個Http request,當(dāng)我試圖在其中查看我的響應(yīng)時,view results tree我成功地獲得了前 20 個請求的響應(yīng)。來自(21 到 100)的后續(xù)請求有空白響應(yīng)。我經(jīng)歷了許多涉及的問題:java.sql.SQLException:無法獲取連接,池錯誤等待空閑對象超時
1 回答

森林海
TA貢獻(xiàn)2011條經(jīng)驗 獲得超2個贊
您沒有關(guān)閉Connection
對象,您必須在 try-with-resources 塊中聲明此類變量:
try (Connection conn = DbConnection.getCon(); PreparedStatement ps = conn.prepareStatement("SELECT id FROM test WHERE id =?;")) {
您還需要關(guān)閉ResultSet
,要么在方法中調(diào)用close
方法,要么ResultSet
使用返回它的新方法將其添加到 try-with-resources 塊
添加回答
舉報
0/150
提交
取消