0

如果你这样做,HikariCP 每次都会初始化并关闭。有什么办法可以避免这种情况并执行各种查询?

// Resource yielding a transactor configured with a bounded connect EC and an unbounded
// transaction EC. Everything will be closed and shut down cleanly after use.
  val transactor: Resource[IO, HikariTransactor[IO]] =
  for {
    ce <- ExecutionContexts.fixedThreadPool[IO](32) // our connect EC
    be <- Blocker[IO] // our blocking EC
    xa <- HikariTransactor.newHikariTransactor[IO](
      "org.h2.Driver", // driver classname
      "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", // connect URL
      "sa", // username
      "", // password
      ce, // await connection here
      be // execute JDBC operations here
    )
  } yield xa

transactor.use(sql"select 42".query[Int].unique.transact[IO]).unsafeRunSync()
4

1 回答 1

1

这不是您Resource在应用程序中使用 s 的方式。

您确实在.use某个main级别上做某事,然后让您需要Transactor传递该值的整个代码,例如:

val actorSystemResource: Resource[IO, ActorSystem]
val transactorResource: Resource[IO, Transactor[IO]]

// initialize controllers, services, etc and create routes for them
def routes(actorSystem: ActorSystem, transactor: Transactor[IO]): Route

val resources = for {
  transactor <- transactorResource
  actorSystem, <- actorSystemResource
  route = routes(actorSystem, transactor)
} yield (transactor, actorSystem, route)

resources.use { case (_, actorSystem, route) =>
  implicit system = actorSystem

  IO.fromFuture {
    Http().bindAndHandle(route, "localhost", 8080)
  }
}

或者,您可以使用resource.allocated,但这几乎肯定是个坏主意,导致代码永远不会运行 的发布部分,Bracket因为它很容易搞砸,例如,如果抛出一些异常则不调用它。

于 2020-06-14T16:35:08.443 回答