假设我有演员A. A期望接收消息,一旦收到消息,它就会发回两条消息。
A extends Actor {
def receive: Receive = {
case M1 =>
context.sender ! M2
context.sender ! M3
}
}
在演员A中,我想发送一条消息然后等待两个回复。 我知道像
这样的方式很容易做出一个回应val task = A ? M1
Await.result(task, timeout)
但我不确定是否可以使用两个连续的消息。
重要的是发送两条单独的消息,因为我需要在另一个地方仅等待它们中的第一个。
答案 0 :(得分:1)
如何将包含M2和M3的元组返回给发件人?
import akka.pattern.ask
import akka.actor.{Props, ActorSystem, Actor}
import akka.util.Timeout
import com.test.A.{M1, M2, M3}
import scala.concurrent.Await
import scala.concurrent.duration._
object Test extends App {
implicit val timeout = Timeout(5 seconds)
val system = ActorSystem("test-system")
val actor = system.actorOf(Props[A], name = "a-actor")
val future = actor ? M1
val await = Await.result(future, Duration.Inf)
println(await)
}
class A extends Actor {
override def receive: Receive = {
case M1 => sender() ! (M2, M3)
}
}
object A {
case object M1
case object M2
case object M3
}
运行此命令将导致:
(M2,M3)
答案 1 :(得分:1)
您可以通过在需要等待两条消息的情况下引入中间Actor来解决此问题。
这个演员看起来像这样:
class AggregationActor(aActor: ActorRef) extends Actor {
var awaitForM2: Option[M2] = None
var awaitForM3: Option[M3] = None
var originalSender: Option[ActorRef] = None
def receive: Receive = {
case M1 =>
// We save the sender
originalSender = Some(sender())
// Proxy the message
aActor ! M1
case M2 =>
awaitForM2 = Some(M2)
checkIfBothMessagesHaveArrived()
case M3 =>
awaitForM3 = Some(M3)
checkIfBothMessagesHaveArrived()
}
private def checkIfBothMessagesHaveArrived() = {
for {
m2 <- awaitForM2
m3 <- awaitForM3
s <- originalSender
} {
// Send as a tuple
s ! (m2, m3)
// Shutdown, our task is done
context.stop(self)
}
}
}
基本上它具有内部状态,并跟踪M1
和M2
响应的到达方式。
你可以使用它:
def awaitBothMessages(input: M1, underlyingAActor: ActorRef, system: ActorSystem): Future[(M2, M3)] = {
val aggregationActor = system.actorOf(Props(new AggregationActor(aActor)))
(aggregationActor ? input).mapTo[(M2, M3)]
}
val system = ActorSystem("test")
val aActor = system.actorOf(Props(new A), name = "aActor")
// Awaiting the first message only:
val firstMessage = aActor ? M1
val first = Await.result(firstMessage, Duration.Inf)
// Awaiting both messages:
val bothMessages: Future[(M2, M3)] = awaitBothMessages(M1, aActor, system)
val both = Await.result(firstMessage, Duration.Inf)