Saturday, 3 September 2016

Building AKKA actor system with Spring on Jetty


The best way to know AKKA or the actor system is to know the Reactive Pattern.


Reactive Design Patterns is a clearly-written guide for building message-driven distributed systems that are resilient, responsive, and elastic. In it, you'll find patterns for messaging, flow control, resource management, and concurrency, along with practical issues like test-friendly designs.


And that’s what Akka is : “Akka is a toolkit and runtime for building highly concurrent, distributed, resilient, message-driven applications on the JVM” (https://www.lightbend.com/community/core-projects/akka)


How does Akka do this ‘reactiveness’ ?

Akka enables this with its reknowed model called ‘Actor Model’. In the Actor Model, an application is broken up into small units of execution called actors. These actors encapsulate the behavior and state of a part of the application. The first part of the definition of actors makes them sound very much like objects in a standard object-oriented design, which is true. However, what distinguishes an actor from a standard object is a third property: communication.

Actors never interact directly with each other and instead communicate via messages. The behavior of an actor is primarily defined by how it handles messages as they are received. Since the state of an actor is isolated from the rest of the system, an actor never has to worry about synchronization issues, such as thread locking, when modifying its state.
(more : https://dzone.com/refcardz/reactive-programming-akka)


How can we build an actor system? 


It’s very easy to create an actor system with a single line of code, 

final ActorSystem system = ActorSystem.create("MySystem"); 
 
But creating an ActorSystem is very expensive, so you want to avoid creating a new one each time you need it. Also your actors should run in the same ActorSystem, unless there is a good reason for them not to. The name of the ActorSystem is also part the the path to the actors that run in it. E.g. if you create an actor in a system named ‘MySystem it will have a path like ‘akka://MySystem/user’. User’s are the actors which you create.You can create an actor with the following line of code.
final ActorRef akkaBot = system.actorOf(Props.create(AkkaBot.class), "akkaBot");

And then ref it as akka://MySystem/user/akkaBot

(more : https://dzone.com/refcardz/reactive-programming-akka)

So How do we solve the proble of creating an AKKA actor system?

The best way which I found is using Spring framework on Jetty Server (As it is verymuch easy to use spring boot classes with Jetty).

Initialize the spring context ( I used WebApplicationInitializer you can also use the dispatcher xml)


Initialize Akka Actor system as a bean using annotation.




That’s it!