【问题标题】:Spray route with ask pattern expects ToResponseMarshallable具有询问模式的喷涂路线需要 ToResponseMarshallable
【发布时间】:2015-07-20 02:59:22
【问题描述】:

我正在尝试我的第一个 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

【问题讨论】:

    标签: scala akka spray


    【解决方案1】:

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

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

    private implicit def ec = actorRefFactory.dispatcher
    

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

    【讨论】:

    • 谢谢你,Elmar,很棒的收获。就是这样。这是我第一次真正看到滥用隐式(包括所有这些磁铁)的缺点。这些技巧真的让我解决问题的能力下降了两个档次。是的,你指出的那篇文章确实很有帮助。荣誉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多