Execute some logic asynchronously in spray routing

纵然是瞬间 提交于 2020-01-05 04:36:11

问题


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.



来源:https://stackoverflow.com/questions/28440896/execute-some-logic-asynchronously-in-spray-routing

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