Tuesday, April 3, 2012

Using Akka Actor in Play2.0

I 've been learning Play framework 2.0 for a while. The documentation did a relatively decent job, it has some minor typos and doesn't cover all the framework features, which are totally understandable since it is still a working progress. The samples ship with the framework are really really good, you can really learn lots from the samples, and of course there is scala doc. However, if you like me: a scala newbie doesn't have too much experiences with Akka, SBT, and other scala libraries play based on; Learning play seems to be an overwhelming task at the beginning. This blog attempts to give an introduce how to use Akka Actor in play 2.0.


Content:
1. How to create actor in Akka 2.0
2. How to wire Akka Actor with play 2.0
3. Commutating between Play Action and Akka Actor via Future and Promise



1. Akka 2.0 (this part base on Akka Actor(scala) Documentation)

I assume you have some understanding about Actor model, if not, dont worry there are plenty articles give you a nice and short introduce about actor model, like this one .

Akka 2.0 uses a different way to create actor: you have to create an actor via Actor System, right now dont worry too much about Actor system: just think it as a container of Akka actors to manage the life cycles of all the Akka actors within the system.









MyActor is your Actor's class name, Props (akka.actor.Props) "is a ActorRef configuration object", and name is an optional parameter to build Actor Path, so you can address your actor by its path. In this tutorial, we won't use this feature.

2. How to wire Akka with Play (this part based on Play Integrate with Akka Doc)
Since Play 2.0 has build-in support for Akka 2.0, so you dont have to create Actor System by yourself







Play docs forgot to mention current, it "implicitly import the current running application in the context.", so play can wire your app with Akka correctly.

3. Commutating between Play Action and Akka Actor via Future and Promise (this part base on Akka Future Documentation and Play Integrate with Akka Doc )

I assume you understand the concept of Future and Promise, they are just generic "data structure to retrieve the result of some concurrent operation". To get Future from an Akka Actor, we have to implicit convert our ActorRef into AskAbleActorRef by import akka.pattern.ask, according to the Akka documentation, it seems you dont have to give a timeout parameter, but according my experience, you have to give a timeout parameter either directly or implicitly, no sure whether it is a bug.