Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

AKKA tutorial

File > New Project > Name it as Akka_Intro > Choose Scala > Create

1. Go to built.sbt file to install the resolver and library dependencies

val AkkaVersion = "2.6.20"

lazy val root = (project in file("."))


.settings(
name := "Akka_Intro",
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor-typed" % AkkaVersion,
"ch.qos.logback" % "logback-classic" % "1.2.3"
)
)

Part 1: Simple Hello World Actor


1. Save below code as HelloWorld.scala

import akka.actor.typed.ActorRef
import akka.actor.typed.ActorSystem
import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import Echo.Message
object Echo {

final case class Message(value: String)

def apply(): Behavior[Message] =


Behaviors.setup { context =>

Behaviors.receiveMessage { message =>


println("receive " + message.value)
Behaviors.same
}
}
}

object MyApp extends App {


val greeterMain: ActorSystem[Echo.Message] = ActorSystem(Echo(), "AkkaQuickStart")

greeterMain ! Message("hello word")


greeterMain ! Message("Charles 2")
}

Short Description of above code:


1 Import all the Akka actor classes you need.
2 Define an Actor, by defining behavior in the special "setup" method.
3 Create a "main" object where you can test things.
4 You needs to give definition of behavior of Actor instance before create Actor
System.

Now that we have an instance of an actor, we send it two messages.

Part 2: Creating an Akka Actor within the guardian actor

import akka.actor.typed.ActorRef
import akka.actor.typed.ActorSystem
import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import Echo.Message

object Repeater {
sealed trait Command
final case object Start extends Command
final case object Stop extends Command
def apply(): Behavior[Command] =
Behaviors.receive { (context, message) =>
message match {
case Start =>
println("starting")
case Stop =>
Behaviors.stopped
}
Behaviors.same
}
}
object Echo {
final case class Message(value: String)
def apply(): Behavior[Message] =
Behaviors.setup { context =>
val actor1: ActorRef[Repeater.Command] = context.spawn(Repeater(), "repe
ater")
Behaviors.receiveMessage { message =>
println("receive " + message.value)
if (message.value == "start"){
actor1 ! Repeater.Start
Behaviors.same
} else if (message.value == "stop") {
Behaviors.stopped
} else {
Behaviors.unhandled
}
}
}
}
import scala.io.StdIn
object MyApp extends App {
val greeterMain: ActorSystem[Echo.Message] = ActorSystem(Echo(), "AkkaQuickS
tart")
var command = StdIn.readLine("command=")
while ( command != "end") {
greeterMain ! Message(command)
command = StdIn.readLine("\ncommand=")
}
}

You might also like