我正在使用HikariDataSource
连接到MariaDB
数据库。以下类返回Connection
。
public class DataSource {
private HikariDataSource ds;
// The constructor takes db name as an argument and creates a new datasource for the connection accordingly.
public DataSource(String dbString) {
HikariConfig config = new HikariConfig();
Map map = DbConfigParser.configKeyValue(dbString);
config.setJdbcUrl(String.valueOf(map.get("uri")));
config.setUsername(String.valueOf(map.get("uname")));
config.setPassword(String.valueOf(map.get("pwd")));
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
}
// Returns a Connection to the database
public Connection getConnection() throws SQLException {
return ds.getConnection();
}
// Close the datasource
public void close(){
if (ds != null) {
ds.close();
}
}
}
这是执行选择查询的方法。该类还包含一个close方法
public List<DataFile> getAllFiles() throws SQLException {
try (Connection connection = dataSource.getConnection();
DSLContext ctx = DSL.using(connection, SQLDialect.MARIADB)) {
List<DataFile> dataFileList = new DataFileQueries().selectQuery(ctx)
.fetchInto(DataFile.class);
if (dataFileList == null || dataFileList.isEmpty()) {
throw new IllegalStateException("The List is Empty!");
}
return dataFileList;
}
}
public void close() {
try {
dataSource.close();
} catch (Exception e) {
LOG.error("A SQLException was caught", e);
}
}
try-with-block自动关闭Connection
对象,但如何关闭连接池?例如,我应该在数据库操作之后调用close方法
public static void main(String[] args) throws SQLException {
DataFileDaoImpl service = new DataFileDaoImpl("testi");
List<DataFile> list = service.getAllFiles();
list.stream().forEach(
e -> System.out.println(e.toString())
);
service.close();
}
当我不调用close()
方法时,我看不到关于启动关闭的任何控制台输出。这是关闭HikariDataSource
和连接池的正确方法吗?
您不需要为每个连接调用DataSource的close():
关闭DataSource及其关联的池。
它仅为application termination定义:
close()
在申请终止时至关重要
您应该继续使用池,注意您正在尝试使用资源关闭(正确)连接
try (Connection connection = dataSource.getConnection()