使用 Slick 3 将数据库连接返回到 HikariCP 池。1.x

Returning db connection to HikariCP pool with Slick 3.1.x

我正在从类型安全配置中设置一个灵活的数据库对象,如下所示:

import com.typesafe.config.Config

class DatabaseService(configKey: String, config: Config) {
  val driver = slick.driver.MySQLDriver
  import driver.api._
  val db = Database.forConfig(configKey, config)
}

配置对象告诉 Slick 使用 HikariCP,像这样:

db {
  numThreads = 5
  connectionTimeout = 30000
  maximumPoolSize = 26
  driver = "com.mysql.jdbc.Driver"
  url = "jdbc:mysql://localhost:3306/some_db?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false"
  user = "root"
  password = "root"
  connectionPool = "HikariCP"
}

实例化 DatabaseService 后,我可以 运行 通过 运行 宁 dbService.db.run(someQuery).

查询

第一个问题是我需要做些什么来从池中获取连接,还是在我调用 db.run() 时在幕后发生?

其次,一旦该查询或查询执行,我如何return将当前数据库连接到连接池?

The first question is do I need to do something to get a connection from the pool or does that happen behind the scenes when I invoke db.run()?

这发生在幕后。

Secondly, once that query or queries execute how do I return the current database connection to the connection pool?

这也在幕后发生。

这里是 relevant code for both questions. Basically, is acquires a session, executes the given action (in your case, someQuery) and then release the session (closes it). Digging a little more at the code, you can see that the JDBC implementation creates a BaseSession which holds a connection and also closes it when the close method is invoked.

此外,来自 the docs

Database connections and transactions are managed automatically by Slick. By default connections are acquired and released on demand and used in auto-commit mode.