类型不匹配:expected :: [String,HNil] => op_rabbit.Handler,actual:String => op_rabbit.Handler

时间:2018-04-22 11:27:33

标签: json scala rabbitmq spray-json

我从here获取了以下代码,以便使用来自RabbitMQ的消息。消费新消息后,我想执行val init = new Initiator()以便对此消息运行一些计算。 在原始代码中,消息解析如下:

package io.ticofab.scalarabbitmqexample.model

import play.api.libs.json.Json

/**
  * This is the kind of object that our listener expects in Json format from the queue. So like
  * {
  * "name" : "xxxx",
  * "version" : 1234
  * }
  *
  * @param name An arbitrary String
  * @param version An arbitrary Int
  */
case class MyObject(name: String, version: Int)

object MyObject {
  implicit def myObjectFormat = Json.format[MyObject]
}

在我的情况下,解析很复杂,我不想在MyObject中解析Json字符串。我想要的是运行body(as[String])而不是body(as[MyObject]) {(请参阅下面的代码)。然后我将使用init.run(obj)import spray.json._内进行解析。

所以,我的目标是将obj转换为String。但如果我这样做,我会收到以下编译错误:

  

类型不匹配:expected :: [String,HNil] => op_rabbit.Handler,   actual:String => op_rabbit.Handler。

package org.test.akka_actors

import akka.actor.{Actor, ActorLogging, Props}
import com.spingo.op_rabbit.Directives._
import com.spingo.op_rabbit.{RabbitControl, Subscription, SubscriptionRef}
import com.typesafe.config.ConfigFactory
import org.test.Initiator
import org.test.akka_actors.QueueListener.{Listen, Terminate}
import org.test.query.QueryObject

import scala.concurrent.ExecutionContext.Implicits.global

object QueueListener {

  case object Listen

  case object Terminate

  def props = Props(new QueueListener)

}

class QueueListener extends Actor with ActorLogging {

  // read info from configuration
  val conf = ConfigFactory.load()
  val QUEUE = conf.getString("op-rabbit.rabbit-queue")

  // instantiate a rabbit mq controller
  val RABBIT_CONTROL = context.actorOf(Props[RabbitControl])

  // references to the queue subscriptions
  var queueSubscription: Option[SubscriptionRef] = None
  override def receive: Receive = {

    case Listen =>
      // initialize a queue subscription
      queueSubscription = Some(
        Subscription.run(RABBIT_CONTROL) {
          channel(qos = 3) {
            consume(queue(QUEUE)) {
              body(as[String]) {
                (obj) =>
                  log.debug(s"received the query $obj")
                  val init = new Initiator()
                  init.run(obj)
                  ack
              }
            }
          }
        }
      )

    case Terminate =>
      // close the subscription
      queueSubscription.foreach(_.close())

  }
}

0 个答案:

没有答案