scala - Scala Doobie & Hikari CP 事务处理
问题描述
如果你这样做,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()
解决方案
这不是您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
因为它很容易搞砸,例如,如果抛出一些异常则不调用它。
推荐阅读
- spring-boot-admin - 墙板不刷新
- angular - 带参数的角度路由,将带参数的路由与不带参数的路由分开
- c++ - 如何使用几种方法处理 1 个数组
- xamarin.forms - 当我在 Frame 布局中添加 ListView 时的额外空间
- amazon-web-services - 执行所有方法后,aws ec2 中的 My 文件的权限被拒绝
- jenkins - exit 0 未触发任何电子邮件
- .net-4.0 - .net 4.0 上的 SAML 2.0
- linux - Unix进程之间的连接,如何获取给定用户名的全名和根目录
- ios - 将 PHLivePhotoView 添加到情节提要
- react-native - 将文本动态添加到 TextInput