要用到HikariDataSource的close方法手动释放的,验证方法是使用MySQL的show processlist
观察连接数的变化。主要代码示例如下:
/**
* 测试释放连接池的数据库连接
*/
@Test
public void testReleaseDBConnection() throws InterruptedException {
HikariConfig config = new HikariConfig();
config.setDriverClassName("com.mysql.jdbc.Driver");
config.setJdbcUrl("jdbc:mysql://10.248.33.118:3306/db_mes_dw?allowMultiQueries=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&autoReconnect=true&failOverReadOnly=false");
config.setUsername("root");
config.setPassword("transsion#123456");
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "1000");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "3000");
JdbcTemplate jdbc = null;
try {
HikariDataSource dataSource = new HikariDataSource(config);
jdbc = new JdbcTemplate(dataSource);
} catch (Exception e) {
//TODO: 存在部分数据库无法连接的情况
}
//为了方便观察连接数
TimeUnit.MINUTES.sleep(1);
HikariDataSource dataSource = (HikariDataSource) jdbc.getDataSource();
dataSource.close();
log.info("数据库连接关闭");
TimeUnit.MINUTES.sleep(1);
}