如何正确关闭HikariCP连接池 [英] How do I properly close a HikariCP Connection Pool
问题描述
我正在使用 HikariDataSource
连接到 MariaDB
数据库。下列类返回 Connection
。
I'm using HikariDataSource
to connect to a MariaDB
database. The following class returns a 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方法
This is the method that executes the select query. The class also contains a close method
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);
}
}
尝试块会关闭 Connection
对象会自动出现,但是如何关闭连接池?我是否应该在数据库操作后调用调用close方法,例如
The try-with-block closes the Connection
object automatically, but how do I close the connection pool? Should I call the call the close method after the database operation, for example
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
和连接池的正确方法吗?
When I don't call the close()
method, I don't see any console output regarding shutdown initiation. Is this the right way to close HikariDataSource
and Connection Pool?
推荐答案
您无需调用DataSource的 close()对于每个连接:
You don't need to call DataSource's close() for every connection:
关闭数据源及其关联的池。
Shutdown the DataSource and its associated pool.
仅为应用程序终止:
close()
在应用程序终止时必不可少
close()
is essential at application termination
继续使用该池,请注意您正在尝试正确使用资源
You should continue working with the pool, notice you are closing (correctly) the connection with try with resources
try (Connection connection = dataSource.getConnection()
这篇关于如何正确关闭HikariCP连接池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!