如何在scala中使方法同步?

时间:2015-01-20 18:47:02

标签: scala asynchronous websocket

在这个方法中,我想看到返回的实际响应(result.toJson.toString或StatusCodes.InternalServerError.toString)而不是空字符串。我怎么能这样做?

def process(msgIn : WebSocketMessageIn, service : ActorRef) : String = {
  import model.Registration
  import model.RegistrationJsonProtocol._

  implicit val timeout = Timeout(10 seconds)

  msgIn.method.toUpperCase match {
    case "POST" =>
      log.debug(s"Handing POST message with body ${msgIn.body}")
      val registration = msgIn.body.convertTo[Registration]
      val future = (service ? PostRegistrationMessage(registration)).mapTo[Registration]
      var response = ""
      future onComplete {
        case Success(result) =>
          response = result.toJson.toString

        case Failure(e) =>
          log.error(s"Error: ${e.toString}")
          response = StatusCodes.InternalServerError.toString
      }
      response

    case "PUT" =>
      s"Handing PUT message ${msgIn.body}"
  }
}

以下是调用该方法并将响应发送到websocket

的代码段
case Message(ws, msg, service) =>
  log.debug("url {} received msg '{}'", ws.getResourceDescriptor, msg)
  val wsMessageIn = msg.parseJson.convertTo[WebSocketMessageIn]
  val response = process(wsMessageIn, service)
  ws.send(response);

更新1:更新为使用Await.result(未来,5000毫秒)而不是未来onComplete {...}'。这是更改的代码段。现在工作,但只是想知道我们将如何处理失败。

msgIn.method.toUpperCase match {
  case "POST" =>
    log.debug(s"Handing POST message with body ${msgIn.body}")
    val registration = msgIn.body.convertTo[ADSRegistration]
    val future = (service ? PostADSRegistrationMessage(registration)).mapTo[ADSRegistration]
    val response = Await.result(future, 5000 millis)
    response.toJson.toString

1 个答案:

答案 0 :(得分:5)

您可以使用阻止的Await.result。像这样:

import scala.concurrent.duration._
val result = Await.result(future, atMost = 10.second)
val response = //result processing

同样,你可以将未来传回来并在send中执行onComplete,这会更具反应性