Sri*_*i K 0 asynchronous scala 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}"
}
}
Run Code Online (Sandbox Code Playgroud)
以下是调用该方法并将响应发送到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);
Run Code Online (Sandbox Code Playgroud)
更新1:更新为使用Await.result(未来,5000毫秒)而不是'future 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
Run Code Online (Sandbox Code Playgroud)
您可以使用Await.result哪个阻止.像这样的东西:
import scala.concurrent.duration._
val result = Await.result(future, atMost = 10.second)
val response = //result processing
Run Code Online (Sandbox Code Playgroud)
虽然如此,你可以通过未来的背部和执行send中onComplete这将是更加反应