我刚开始使用scala,想建立与数据库的连接。
(我的知识源于 scala/doobie 教程的 https://www.scala-exercises.org/(
现在这是代码:
import doobie._
import doobie.implicits._
import cats.effect._
import cats.implicits._
import doobie.hikari._
...
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:mysql://localhost:3306/libraries", // connect URL
"root", // username
"", // password
ce, // await connection here
be // execute JDBC operations here
)
} yield xa
当我尝试构建我的代码时,我收到以下错误消息:
错误:(25, 53( 找不到 ContextShift [cats.effect.IO] 的隐式值:
从效果库中导入上下文转换[cats.effect.IO]
如果使用 IO,请使用 cats.effect.IOApp 或使用 cats.effect.IO.contextShift 构建一个 xa <- HikariTransactor.newHikariTransactor[IO](
现在我有两个问题:
- 问题到底出在哪里?
- 我该如何解决?
编译器在隐式作用域中找不到ContextShift[IO]
实例的问题,这是某些方法所必需的(不确定确切是哪个(。 您需要在隐式作用域中声明自己的范围,例如
val dbExecutionContext = ExecutionContext.global // replace with your DB specific EC.
implicit val contextShift: ContextShift[IO] = IO.contextShift(dbExecutionContext)
或作为错误建议的消息cats.effect.IOApp
已将ContextShift[IO]
声明为protected implicit def
- 请参阅 https://github.com/typelevel/cats-effect/blob/master/core/shared/src/main/scala/cats/effect/IOApp.scala#L83,您可以在此代码所在的位置使用和传递引用。 但要小心,因为它使用 Scala 默认的全局执行上下文。
希望这有帮助!