找不到类别cats.data.Chain $ Wrap的编解码器

时间:2019-05-09 19:33:53

标签: scala akka scala-cats alpakka

我正在使用https://doc.akka.io/docs/alpakka/current/mongodb.html API与MongoDB通信,如下所示:

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.alpakka.mongodb.scaladsl.MongoSink
import akka.stream.scaladsl.Source
import cats.data.Chain
import com.mongodb.reactivestreams.client.MongoClients
import org.mongodb.scala.bson.codecs.DEFAULT_CODEC_REGISTRY
import org.mongodb.scala.bson.codecs.Macros._
import org.bson.codecs.configuration._

import scala.util.{Failure, Success}

object Main extends App {
  implicit val system = ActorSystem()
  implicit val mat = ActorMaterializer()
  implicit val executor = system.dispatcher

  val preFailure = MsgPreFailure("Hello", Chain("Foo", "Too"))
  val codecRegistry = CodecRegistries
    .fromRegistries(CodecRegistries.fromProviders(classOf[MsgPreFailure]), DEFAULT_CODEC_REGISTRY)

  private val client = MongoClients.create("mongodb://localhost:27017")
  private val db = client.getDatabase("test")
  private val preFailureColl = db
    .getCollection("msg", classOf[MsgPreFailure])
    .withCodecRegistry(codecRegistry)

  val conn = Source
    .single(preFailure)
    .runWith(MongoSink.insertOne(preFailureColl))

  conn.onComplete {
    case Success(value) =>
      println(value)
    case Failure(ex) =>
      println(ex.getMessage)
  }

} 

作为错误消息,我得到:

Can't find a codec for class cats.data.Chain$Wrap.  

如何编写编解码器?

0 个答案:

没有答案