java - 如何正确关闭 HikariCP 连接池

标签 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();
    }
  }
}

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

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()对于每个连接:

Shutdown the DataSource and its associated pool.

仅为application termination定义:

close() is essential at application termination

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

try (Connection connection = dataSource.getConnection()

关于java - 如何正确关闭 HikariCP 连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54732562/

相关文章:

Java线程启动时间

java - 无法解析 setOnClickListener 中的符号

c# - Combobox SelectedValue 返回 System.Data.DataRowView 甚至转换为字符串

tomcat连接池

java - Tomcat 连接池配置 : DataSource type and "Too many connection" error

java - Spring data Jpa 将具有某些不同字段的多个 SQL View 映射到单个实体中

java - EXT GWT 将所选项目绑定(bind)到新的空网格

kendo-ui - Kendo DataSource 单行读取

java - JDBC 连接意外变为空

c# - Java Service 类,类似于 C# 的 ServiceBase