在喷涂路由中异步执行一些逻辑 [英] Execute some logic asynchronously in spray routing

查看:92
本文介绍了在喷涂路由中异步执行一些逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的简单路由应用程序:

  object Main通过SimpleRoutingApp {隐含

来扩展应用程序val system = ActorSystem( my-system)

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

导入格式。UsageJsonFormat._
导入spray.httpx.SprayJsonSupport._

path(){
get {
complete( OK)
}
}〜
path( meter / JavaUUID){
meterUUID => pathEnd {
post {
实体(as [用法]){
用法=>
//异步执行某些逻辑
//不要等待结果
complete( OK)
}
}
}
}
}
}

我想要实现的是执行一些逻辑在我的path指令中异步执行,不要等待结果并立即返回HTTP 200 OK。



我对Scala还是很陌生,请喷雾并想知道是否有喷雾方式解决此特定问题。否则,我会转向为每个请求创建 Actor 并让它完成任务的方向。请指教。

解决方案

没有特殊的方式来处理此问题:只需触发您的异步操作即可(返回 Future ,发送给演员的消息,无论如何),然后立即调用 complete

  def doStuffAsync =未来{
//实际上是任何东西
}

path( meter / JavaUUID){meterUUID => ;
pathEnd {
post {
实体(as [用法]){用法=>
doStuffAsync()
complete( OK)
}
}
}
}

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.

解决方案

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.

这篇关于在喷涂路由中异步执行一些逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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