带有ask模式的喷涂路径需要ToResponseMarshallable

时间:2015-07-19 14:54:34

标签: scala akka spray

我正在尝试我的第一个Spray + Akka项目工作。

虽然这看起来很简单,但我仍然会遇到unmarshaller的类型错误(我不需要,我还没有返回一个字符串,因为我最终只生成XML)

package com.example.actors

import akka.actor.{Props, ActorContext, Actor}
import akka.util.Timeout
import spray.http.CacheDirectives.`max-age`
import spray.http.HttpHeaders.`Cache-Control`
import spray.routing._
import spray.http._
import MediaTypes._
import scala.concurrent.duration._

class SprayActor extends Actor with DefaultService {
  def actorRefFactory = context
  def receive = runRoute(defaultRoute)
}

trait DefaultService extends HttpService {
  def actorRefFactory: ActorContext

  lazy val feedActor = actorRefFactory.system.actorOf(Props[MainFeedActor])

  import akka.pattern.ask

  implicit val timeout = Timeout(5 seconds) // needed for `?` below

  val defaultRoute = path("rss") {
    get {
      respondWithMediaType(`text/xml`) {
        respondWithHeaders(`Cache-Control`(`max-age`(0))) {
          complete {
            (feedActor ? "rss").mapTo[String]
          }
        }
      }
    }
  }
}

class MainFeedActor extends Actor {
  val log = Logging(context.system, this)

  override def receive: Receive = {
    case "rss" => "<xml>test</xml>"
  }

以下是编译器错误:

[error] src/main/scala/com/example/actors/SprayActor.scala:31: type mismatch;
[error]  found   : scala.concurrent.Future[String]
[error]  required: spray.httpx.marshalling.ToResponseMarshallable
[error]             (feedActor ? "rss").mapTo[String]
[error]                                      ^
[error] one error found
[error] (compile:compile) Compilation failed

1 个答案:

答案 0 :(得分:3)

使用magnet pattern进行喷射中的响应编组非常复杂,这使得它非常强大且可调节(例如,通过自动添加SprayJsonSupport的导入,所有JSON兼容的案例类都是有效的响应)。

许多默认分辨率不起作用,因为缺少一个或另一个隐式。在这种情况下,对于正在运行的期货,缺少ExecutionContext。尝试将此添加到服务:

private implicit def ec = actorRefFactory.dispatcher

绝对给链接的文章一个阅读,帮助我更好地理解喷雾。