Java 代码测试 Druid 数据库连接池的参数设置,并测试连接数不足时的报错情况。
依赖配置
引入 Druid 依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
Java 实现代码
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.stat.DruidStatManagerFacade;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DruidConnectionTest {
public static void main(String[] args) {
// 初始化 Druid 数据源
DruidDataSource dataSource = new DruidDataSource();
try {
// 配置数据源参数
dataSource.setUrl("jdbc:mysql://localhost:3306/testdb");
dataSource.setUsername("root");
dataSource.setPassword("password");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setInitialSize(2); // 初始连接数
dataSource.setMinIdle(1); // 最小空闲连接数
dataSource.setMaxActive(5); // 最大连接数
dataSource.setMaxWait(2000); // 获取连接的最大等待时间(毫秒)
dataSource.setTimeBetweenEvictionRunsMillis(60000); // 检测间隔时间
dataSource.setValidationQuery("SELECT 1"); // 用于测试连接的 SQL
dataSource.setTestWhileIdle(true); // 是否在空闲时检测连接有效性
dataSource.setTestOnBorrow(false); // 获取连接时是否检测有效性
// 模拟多个线程请求连接
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(() -> {
try (Connection connection = dataSource.getConnection()) {
System.out.println(Thread.currentThread().getName() + " 获取连接成功");
Thread.sleep(3000); // 模拟使用连接的耗时操作
} catch (SQLException | InterruptedException e) {
System.err.println(Thread.currentThread().getName() + " 获取连接失败:" + e.getMessage());
}
});
threads.add(thread);
}
// 启动线程
for (Thread thread : threads) {
thread.start();
}
// 实时打印连接池状态
monitorConnectionPool(dataSource);
// 等待所有线程完成
for (Thread thread : threads) {
thread.join();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据源
if (dataSource != null) {
dataSource.close();
}
}
}
/**
* 实时监控连接池状态,打印总连接数、活动连接数、空闲连接数。
*
* @param dataSource Druid 数据源
*/
private static void monitorConnectionPool(DruidDataSource dataSource) {
new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("==== Druid Connection Pool Stats ====");
System.out.println("总连接数 (MaxActive): " + dataSource.getMaxActive());
System.out.println("活动连接数 (Active): " + dataSource.getActiveCount());
System.out.println("空闲连接数 (Idle): " + dataSource.getPoolingCount());
System.out.println("--------------------------------------");
Thread.sleep(1000); // 每秒刷新一次
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
}
}
输出
假设 MaxActive
设置为 5,线程数为 10,以下是可能的运行结果:
==== Druid Connection Pool Stats ====
总连接数 (MaxActive): 5
活动连接数 (Active): 5
空闲连接数 (Idle): 0
--------------------------------------
Thread-1 获取连接成功
Thread-2 获取连接成功
Thread-3 获取连接成功
Thread-4 获取连接成功
Thread-5 获取连接成功
Thread-6 获取连接失败:等待超时
Thread-7 获取连接失败:等待超时
注意
- 根据实际情况调整数据库连接参数。
- 在线上环境中请谨慎设置
MaxActive
和MaxWait
,避免因连接池耗尽而导致业务不可用。