learning scala akka ask_pattern

时间:2023-03-09 08:09:31
learning scala akka ask_pattern
package com.example

import  akka.actor._
import akka.util.Timeout object Tutorial_03_Ask_Pattern extends App {
val system = ActorSystem("DonutStoreActorySystem") val donutInfoActor = system.actorOf(Props[DonutInfoActor], name="DonutInfoActor") import DonutStoreProtocal._
import akka.pattern._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._ implicit val timeout = Timeout( second) val vanillaDonutFound = donutInfoActor ? Info("vanilla")
for {
found <- vanillaDonutFound
} yield (println(s"Vanilla donut found = $found")) val glazedDountFound = donutInfoActor ? Info("glazed")
for {
found <- glazedDountFound
} yield (println(s"Glazed donut found = $found")) Thread.sleep() system.terminate(); object DonutStoreProtocal{
case class Info(name: String)
} class DonutInfoActor extends Actor with ActorLogging {
import Tutorial_03_Ask_Pattern.DonutStoreProtocal._ override def receive: Receive = {
case Info(name) if name == "vanilla" =>
log.info(s"Found valid $name donut")
sender ! true
case Info(name) =>
log.info(s"$name donut is not supported")
sender ! false
}
}
}

result:

Vanilla donut found = true
[INFO] [// ::51.502] [DonutStoreActorySystem-akka.actor.default-dispatcher-] [akka://DonutStoreActorySystem/user/DonutInfoActor] Found valid vanilla donut
Glazed donut found = false
[INFO] [// ::51.512] [DonutStoreActorySystem-akka.actor.default-dispatcher-] [akka://DonutStoreActorySystem/user/DonutInfoActor] glazed donut is not supported