如何正确关闭HikariCP连接池

14

我正在使用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();
    }
  }
}

这是执行选择查询的方法。该类还包含一个关闭方法。

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和连接池的正确方式吗?

1个回答

17

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

关闭DataSource及其关联的池。

它仅在应用程序终止时定义:

close()在应用程序终止时是必需的

你应该继续使用池,注意你正在使用try with resources正确地关闭连接

try (Connection connection = dataSource.getConnection()

非常感谢您的解释。那么,在应用程序终止时仅调用 close() 而不是在每个 Connection 关闭后都调用,这样做是可以的吗? - Roshan Upreti
@RoshanUpreti 是的 - user7294900
3
如果您在每次连接后关闭数据源,那么您就会失去连接池的任何好处(更不用说可能会破坏从池中检出的连接的并发使用)。@RoshanUpreti - Mark Rotteveel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接