Spray's `detach` Directive

大憨熊 提交于 2019-12-01 10:25:09

问题


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.


回答1:


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:

  • https://github.com/spray/spray/issues/717
  • https://github.com/spray/spray/issues/872

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.




回答2:


Without detach spray will process all requests one by one, while with detach it'll process them parallel. If you can process this requests in parallel, you'd better use detach for better performance.



来源:https://stackoverflow.com/questions/31364405/sprays-detach-directive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!