Spray 的 `detach` 指令 [英] Spray's `detach` Directive

查看:69
本文介绍了Spray 的 `detach` 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下喷码:

object Main 使用 SimpleRoutingApp 扩展 App {隐式 val 系统 = ActorSystem("my-system")val 管道:HttpRequest =>Future[String] = sendReceive ~>解组[字符串]启动服务器(接口 =本地主机",端口 = 8080){路径(去"){得到 {分离(){完全的 {val req = Post("http://www.google.com") ~>addHeader("Foo", "bar")管道(req).recoverWith[String]{ case _ =>未来{错误!"} }}}}}}}

我将 complete 函数放在 分离 指令.

文档解释了 detach 将:在未来执行内部路由.

性能的角度来看,使用(或不使用)detach有什么意义?

我看了这个相关的答案,但它侧重于如何使用分离.

解决方案

detach 通常是需要的,因为路由在 actor 中同步运行.这意味着当 HttpRequest 被路由时,actor 不能同时处理任何其他消息.

但是,像使用 Future 完成或使用 FutureDirectives 之一等异步路由位也将释放原始路由actor 以处理新请求.

因此,在路由本身是瓶颈或您同步完成请求的情况下,添加 detach 可能会有所帮助.在你上面的例子中,你已经完成了一个 Future 并且有一个相对简单的路由结构,在这种情况下添加 detach 不会有太大帮助(或者甚至可能引入一点点延迟).

此外,detach 带有一些不一致之处,您可以在此处阅读:

使用 detach 的替代方法是使用 per-request-actors.

在 akka-http 中,路由是在 Futures 之上实现的,以尽可能异步并且不再局限于参与者,因此不需要 detach 并因此被删除.>

Given the following Spray code:

object Main extends App with SimpleRoutingApp {

  implicit val system = ActorSystem("my-system")

  val pipeline: HttpRequest => Future[String] = sendReceive ~> unmarshal[String]

  startServer(interface = "localhost", port = 8080) {
    path("go") {
      get { 
        detach() { 
          complete {
            val req = Post("http://www.google.com") ~> addHeader("Foo", "bar")
            pipeline(req).recoverWith[String]{ case _ => Future { "error!" } }
          }
        }
      }
    } 
  }
}

I put the complete function within the detach directive.

The docs explain that detach will: execute the inner route inside a future.

What's the significance of using (or not) detach - from a performance perspective?

I looked at this related answer, but it focuses on how to use detach.

解决方案

detach is usually needed because routing runs synchronously in an actor. This means that while an HttpRequest is routed, the actor cannot process any other messages at the same time.

However, routing bits that are asynchronous like completing with a Future or using one of the FutureDirectives will also free the original routing actor for new requests.

So, in cases where routing itself is the bottleneck or you complete a request synchronously, adding detach may help. In your case above, you already complete with a Future and have a relatively simple routing structure in which case adding detach won't help much (or may even introduce a tiny bit of latency).

Also, detach comes with some inconsistencies you can read about here:

An alternative to using detach is using per-request-actors.

In akka-http, routing is implemented on top of Futures to be as asynchronous as possible and not confined to an actor any more so that detach isn't needed and was removed therefore.

这篇关于Spray 的 `detach` 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆