Skip to content

Instantly share code, notes, and snippets.

@glidester
Created March 27, 2014 14:49
Show Gist options
  • Save glidester/9809206 to your computer and use it in GitHub Desktop.
Save glidester/9809206 to your computer and use it in GitHub Desktop.
Akka Actor per request in Play2 Controller
object BlackListController extends Controller {
val myActor = Akka.system.actorOf(Props[LicenceBlackList], name = "LicenceBlackListActor")
type OptionalBlacklistEntry = Option[BlacklistEntry]
def get(key: String) = Action.async {
//we will use this promise to create a future (read handle) which will be returned from this action. This future will complete when the promise is successfully populated with value
val p = Promise[Option[BlacklistEntry]]
//create a new actor per request instance to handle this particular request
val replyTo = Akka.system.actorOf( Props( new Actor {
def receive = {
case reply: OptionalBlacklistEntry =>
p.success(reply)
context.stop(self) //terminate this actor instance
}
}))
//send message to another actor
myActor.tell(msg = ReadEntry(key), sender = replyTo)
//transforming the actor response to Play result
p.future.map(response => {
response match {
case Some(blackListEntry) => Ok(Json.toJson( blackListEntry ))
case None => NotFound
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment