Akka is a part of the Typesafe Reactive Platform, which is similar to the Play Framework. According to their website:
Akka is a toolkit and runtime used to build highly concurrent, distributed, and fault-tolerant event-driven applications on the JVM.
Akka implements a version of the Actor Model, which is commonly called Akka Actors and is available for both Java and Scala. According to the Akka documentation, Actors give you:
Akka Actors are available as a library and can be used within a project by adding them into the dependencies:
libraryDependencies ++= Seq( "com.typesafe.akka" %% "akka-actor" % "2.3.4" )
We can then define an actor by extending the Actor trait and defining the behavior in the receive
method. Let's build an Actor, which reverses any string message it receives:
class Reverser extends Actor { def receive = { case s:String => println( s.reverse) case _ => println("Sorry, didn't quite understand that. I can only process a String.") } } object Reverser { def props = Props(classOf[Reverser]) }
To use the actor, we first need to initialize ActorSystem
:
val system = ActorSystem("demoSystem")
Now we can get a reference of the actor by using the actorOf
method:
val demoActor = system.actorOf(Reverser.props, name = "demoActor")
This reference can then be used to send messages:
demoActor ! "Hello, How do u do?" demoActor ! "Been Long since we spoke" demoActor ! 12345
Now let's run the application and see what the actor does:
> run [info] Compiling 1 Scala source to /AkkaActorDemo/target/scala-2.10/classes... [info] Running com.demo.Main ?od u od woH ,olleH ekops ew ecnis gnoL neeB Sorry, didn't quite understand that I can only process a String.
Suppose we wanted to define an Actor that accepted minLength
and MaxLength
as arguments, we would need to modify the Reverser
class and its companion as follows:
class ReverserWithLimit(min:Int,max:Int) extends Actor { def receive = { case s:String if (s.length> min & s.length<max)=> println( s.reverse) case _ => println(s"Sorry, didn't quite understand that. I can only process a String of length $min-$max.") } } object ReverserWithLimit { def props(min:Int,max:Int) = Props(classOf[Reverser],min,max) }
For more details on Akka actors, refer to http://akka.io/docs/.
3.143.254.90