4

我刚开始使用 scala 并想建立与我的数据库的连接。

(我的知识来自https://www.scala-exercises.org/上的 scala/doobie 教程)

现在这里是代码:

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] 的隐式值:

  • 从效果库中导入 ContextShift[cats.effect.IO]

  • 如果使用 IO,请使用cats.effect.IOApp 或使用cats.effect.IO.contextShift xa <- HikariTransactor.newHikariTransactor[IO](

现在我有两个问题:

  1. 究竟是什么问题?
  2. 我如何解决它?
4

1 回答 1

3

编译器无法在隐式范围内找到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 默认的全局执行上下文。

希望这可以帮助!

于 2020-02-14T14:16:28.400 回答