Execute some logic asynchronously in spray routing

2019-08-02 11:26发布

问题:

Here is my simple routing application:

object Main extends App with SimpleRoutingApp {

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

    startServer(interface = "0.0.0.0", port = System.getenv("PORT").toInt) {

        import format.UsageJsonFormat._
        import spray.httpx.SprayJsonSupport._

        path("") {
            get {
                complete("OK")
            }
        } ~
            path("meter" / JavaUUID) {
                meterUUID => pathEnd {
                    post {
                        entity(as[Usage]) {
                            usage =>
                                // execute some logic asynchronously
                                // do not wait for the result
                                complete("OK")
                        }
                    }
                }
            }
    }
}

What I want to achieve is to execute some logic asynchronously in my path directive, do not wait for the result and return immediately HTTP 200 OK.

I am quite new to Scala and spray and wondering if there is any spray way to solve this specific problem. Otherwise I would go into direction of creating Actor for every request and letting it to do the job. Please advice.

回答1:

There's no special way of handling this in spray: simply fire your async action (a method returning a Future, a message sent to an actor, whatever) and call complete right after.

def doStuffAsync = Future {
   // literally anything
}

path("meter" / JavaUUID) { meterUUID =>
  pathEnd {
    post {
      entity(as[Usage]) { usage =>
        doStuffAsync()
        complete("OK")
      }
    }
  }
}

Conversely, if you need to wait for an async action to complete before sending the response, you can use spray-specific directives for working with Futures or Actors.



标签: scala akka spray