如何正确关闭HikariCP连接池

Ros*_*eti 6 java datasource connection-pooling hikaricp

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是执行选择查询的方法。该类还包含一个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);
 }
}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

当我不调用该close()方法时,看不到任何有关关闭启动的控制台输出。这是关闭HikariDataSource连接池的正确方法吗?

use*_*900 5

您不需要为每个连接调用DataSource的close()

关闭数据源及其关联的池。

它仅用于终止应用程序

close() 在终止应用程序时必不可少

您应该继续使用该池,请注意您正在尝试正确使用资源来关闭(正确)连接

try (Connection connection = dataSource.getConnection()
Run Code Online (Sandbox Code Playgroud)

  • @RoshanUpreti 如果您在每次连接后关闭数据源,您就会放弃连接池的任何好处(更不用说您可能会破坏从池中检出的连接的并发使用)。 (2认同)