2015-01-20 54 views
0

在這個方法中,我希望看到返回的實際響應(result.toJson.toString或StatusCodes.InternalServerError.toString)而不是空字符串。我怎樣才能做到這一點?如何使方法在scala中同步?

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}" 
    } 
} 

這裏是代碼片段調用該方法,併發送響應於網頁套接字

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); 

UPDATE 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 

回答

4

您可以使用阻止的Await.result。事情是這樣的:

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

其實都一樣,你可以通過未來的背部和執行在onCompletesend這將是更加反應

+0

感謝。忘記.....現在固定 – 2015-01-20 18:58:14

+0

改變了代碼到 響應= Await.result(今後,5000毫秒時間) 響應 獲取此編譯錯誤 [錯誤]實測值:scala.concurrent.Future [model.Registration ] [error] required:scala.concurrent.Awaitable [String] [error] response = Await.result(future,5000 millis) – 2015-01-20 19:10:01

+0

你可以發佈你的新代碼來驗證,但看着錯誤,我猜測您正試圖將結果設置爲響應,而結果將返回註冊。我不知道這種類型,所以這就是爲什麼我只是把評論....我的猜測是它應該是結果(...)toJson.toString – 2015-01-20 19:29:55