Introduction
Let’s review the main concepts in akka
Akka
Step 1: Create ActorSystem
1
|
final ActorSystem system = ActorSystem.create()
|
The ActorSystem
maintains ThreadPools
and is up until you shut it down! and is a factory for creating actors and managing their lifecycle.
Step 2: Code an actor
1
2
3
4
5
6
7
8
|
public class MyAkkaActor extends AbstractActor {
public Receive createReceive() {
return receiveBuilder()
.match(DoIt.class, this::onDoIt)
.match(StopDoingIt.class, this.onStopDoingIt)
.build();
}
}
|
Step 3: Instantiate top level topology actor
1
|
final Actor myAkkaActor = system.actorOf(Props.create(MyAkkaActor.class), "myAkkaActor");
|
if your actor needs a child actor use the ActorContext
to create it, this is how we build the actor hierarchy.
Step 5: Code a message
You don’t call methods
on an actor your send it immutable objects
- messages
1
2
3
4
5
6
7
8
|
public static class DoIt {
public final int howManyTimes;
public DoIt(int howManyTimes) {
this.howManyTimes = howManyTimes;
}
}
public static class StopDoingIt {}
public static class FasterFaster {}
|
Step 6: Call an actor with a message
Ordering of messages from same actor is preserved. different sernders can be interleaved.
1
2
|
myAkkaActor.tell(new DoIt(2), ActorRef.noSender())
myAkkaActor.tell(new DoIt(1), getSelf())
|
Step 7: Send a message back to calling actor
1
|
getSender().tell(new DoIt(1), getSelf())
|
if no sender, for example message was not sent from an actor message would be sent to deadLetters
. deadLetter
is a special Actor
.
Step 7: Create child actor
1
2
3
|
getContext().actorOf(Props.create(MyAkkaActor.class));
getContext().getChildren()[0].tell(new DoThis(1), getSelf());
getContext().parent()
|
Step 8: Fault tolerance and self healing
By default parent actor restarts it’s children in case of failure but you can change that.
1
|
.match(Terminated.class, this::onChildTerminated)
|
Akka parts
- Client uses
ActorRef
to send a message to a real actor.
ActorRef
delivers the message asynchronously to the real actor.
Dispatcher
for that actor notified a message received.
Dispatcher
schedules the actor for execution.
Actor
while running other messages are queued.
Actor
when done can send message back to ActorRef
- repeat
Comments