Scala Doobie和Hikari CP交易处理

时间:2020-06-14 03:50:52

标签: scala hikaricp doobie

如果执行此操作,则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()

1 个答案:

答案 0 :(得分:1)

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

您确实在.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的发行版部分,因为它很容易搞乱,例如如果引发某些异常,则不调用它。