【问题标题】:how to respond to a request with a dependency on another actor?如何响应依赖于另一个参与者的请求?
【发布时间】:2016-07-11 15:59:30
【问题描述】:

这可能是一个愚蠢的问题,但我需要问,因为我还没有找到答案。我已经使用带有路由的 akka-http 以及带有 a
的路径的典型路由模式 完成一个 HttpRequest。

例如:

~ path("reactJS") {
  complete(
    HttpResponse(entity = HttpEntity(ContentTypes.`text/html(UTF-8)`, Source.fromFile(reactJS).mkString))
  )
}

但是,我希望有一个单独的参与者来处理文件系统,然后在我看来,我希望服务器将请求传递给文件处理程序参与者。所以我的问题是,如何自然地完成一个依赖于另一个参与者的请求?我猜那么服务器的路由看起来像:

 ~ path("patient" / IntNumber) { index =>
      FileHandler ! index
   }

class FileHandler extends Actor{
  def receive = {
    case msg:Int => sender() ! file handling

}

并且请求的服务必须是服务器的接收方法中的一个案例,对吗?

调查:How to respond with the result of an actor call?

【问题讨论】:

    标签: akka akka-http


    【解决方案1】:

    我认为你最好的选择是使用 ask 模式 (?),然后在路由树中使用 onComplete 指令来处理从 ask 返回的 Future。以您的示例为例,对其进行一些修改以显示如何利用 ask 如下所示:

    path("patient" / IntNumber) { index =>
      import akka.pattern.ask
      implicit val timeout = akka.util.Timeout(10 seconds)
      val fut = (fileHandlerActor ? index).mapTo[String]
      onComplete(fut){
        case util.Success(fileData) => 
          complete(HttpResponse(entity = HttpEntity(
            ContentTypes.`text/html(UTF-8)`, fileData))
    
        case util.Failure(ex) =>
          complete(HttpResponse(StatusCodes.InternalServerError))
      }
    }
    

    这里的假设是您的参与者正在使用将成为 HTTP 响应实体的字符串进行响应。此外,该超时是使用 ask 的要求,但您可以在代码的其他地方轻松定义它,只要它在此处的范围内。

    【讨论】:

    • 我认为我在将其复制为工作代码时遇到了问题(未指定的值参数:data:Source[ByteString, Any])
    • 不需要写 onComplete (fut) 吗?
    • @stian,是的,你是正确的,我在没有检查编译的情况下进行了所有这些更改。我现在向onComplete 添加了正确的呼叫。对不起。
    • 尝试弄清楚其实也很有趣:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2019-12-25
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多