More Actors
To illustrate using two actors in an Akka system, let's create a simple Scala application where one actor sends a message to another actor. This example demonstrates basic actor interaction, message passing, and how actors can work together to achieve a task.
We'll create a scenario with two actors: Sender
and Receiver
. The Sender
actor will send a greeting message to the Receiver
actor, which will then log the greeting.
Step 1: Define Messages
First, define the messages that actors will use for communication. For simplicity, we'll have a single message type that includes a string payload.
sealed trait Message
final case class Greet(message: String) extends Message
Step 2: Define the Receiver Actor
The Receiver
actor will handle the Greet
message by printing it to the console.
import akka.actor.typed.{ActorRef, Behavior}
import akka.actor.typed.scaladsl.Behaviors
object Receiver {
def apply(): Behavior[Message] = Behaviors.receive { (context, message) =>
message match {
case Greet(greeting) =>
context.log.info(s"Received message: $greeting")
Behaviors.same
}
}
}
Step 3: Define the Sender Actor
The Sender
actor will send a Greet
message to the Receiver
. It needs a reference to the Receiver
actor, which we'll pass as a constructor parameter.
object Sender {
def apply(receiver: ActorRef[Message]): Behavior[Message] = Behaviors.setup { context =>
// Sending the greeting message to the receiver
receiver ! Greet("Hello, Akka Typed Actors!")
Behaviors.same
}
}
Step 4: Set Up the Actor System
Now, set up the ActorSystem
, create both actors, and start the interaction.
import akka.actor.typed.ActorSystem
object AkkaQuickStart extends App {
// Create the Actor System
val actorSystem: ActorSystem[Message] = ActorSystem(Receiver(), "receiverSystem")
// Create the Receiver Actor
val receiver: ActorRef[Message] = actorSystem.systemActorOf(Receiver(), "receiver")
// Create the Sender Actor and pass the Receiver's ActorRef
actorSystem.systemActorOf(Sender(receiver), "sender")
}
In this example, when the AkkaQuickStart
application runs, it sets up an ActorSystem
and creates both Sender
and Receiver
actors. The Sender
immediately sends a Greet
message to the Receiver
upon initialization, demonstrating basic actor communication. The Receiver
actor logs the message to the console as its way of "handling" the message.