Op-Rabbit with Spray-Json in Akka Http

时间:2016-02-19 11:59:41

标签: scala rabbitmq akka akka-stream akka-http

我正在尝试使用库Op-Rabbit来使用Akka-Http项目中的RabbitMQ队列。

我想使用Spray-Json进行编组/联合编组。

import com.spingo.op_rabbit.SprayJsonSupport._
import com.spingo.op_rabbit.stream.RabbitSource
import com.spingo.op_rabbit.{Directives, RabbitControl}

object Boot extends App with Config with BootedCore with ApiService  {
  this: ApiService with Core =>

 implicit val materializer = ActorMaterializer()


 Http().bindAndHandle(routes, httpInterface, httpPort)
 log.info("Http Server started")

  implicit val rabbitControl = system.actorOf(Props[RabbitControl])

  import Directives._
  RabbitSource(
    rabbitControl,
    channel(qos = 3),
    consume(queue(
      "such-queue",
      durable = true,
      exclusive = false,
      autoDelete = false)),
    body(as[User])). 
    runForeach { user =>
    log.info(user)
  } // after each successful iteration the message is acknowledged.
}

在另一个文件中:

case class User(id: Long,name: String)

object JsonFormat extends DefaultJsonProtocol {
  implicit val format = jsonFormat2(User)
}

我得到的错误是:

could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[*.*.models.User]
[error]     body(as[User])). // marshalling is automatically hooked up using implicits
[error]            ^
[error]could not find implicit value for parameter um: com.spingo.op_rabbit.RabbitUnmarshaller[*.*.models.User]
[error]       body(as[User])
[error]              ^
[error] two errors found

我不确定如何让op-rabbit spray-json支持正常工作。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

尝试为User类提供一个隐式编组器,就像它们为Int(在RabbitTestHelpers.scala中)一样:

implicit val simpleIntMarshaller = new RabbitMarshaller[Int] with RabbitUnmarshaller[Int] {
    val contentType = "text/plain"
    val contentEncoding = Some("UTF-8")

    def marshall(value: Int) =
      value.toString.getBytes

    def unmarshall(value: Array[Byte], contentType: Option[String], charset: Option[String]) = {
      new String(value).toInt
    }
  }