具有询问模式的喷射路线需要 ToResponseMarshallable

Spray route with ask pattern expects ToResponseMarshallable

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

虽然这看起来很简单,但我仍然遇到解组器的类型错误(我不需要,我返回一个字符串,因为我最终只会产生 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

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

很多默认解决方案都不起作用,因为缺少一个或另一个隐式解决方案。在这种情况下,为了使期货正常工作,缺少 ExecutionContext。尝试将其添加到服务中:

private implicit def ec = actorRefFactory.dispatcher

一定要读一读链接的文章,帮助我更好地理解喷雾。