我正在使用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.
如何编写编解码器?