gpt4 book ai didi

scala - 如何使用Behavior.receiveMessage处理生命周期信号

转载 作者:行者123 更新时间:2023-12-02 03:13:34 25 4
gpt4 key购买 nike

我有一个 Actor ,其创建如下:

    Behaviors.setup { context =>
val greeter = context.spawn(HelloWorld.greeter, "greeter")

Behaviors.receiveMessage { message =>
val replyTo = context.spawn(HelloWorldBot.bot(greetingCounter = 0, max = 3), message.name)
greeter ! HelloWorld.Greet(message.name, replyTo)
Behaviors.same
}
}

我想在Behaviors.receiveMessage中处理Signals消息(例如PostStop),并且在文档中说:

Simplified version of Receive with only a single argument - the message to be handled. Useful for when the context is already accessible by other means, like being wrapped in an setup or similar. Construct an actor behavior that can react to both incoming messages and lifecycle signals. After spawning this actor from another actor (or as the guardian of an akka.actor.typed.ActorSystem) it will be executed within an ActorContext that allows access to the system, spawning and watching other actors, etc. Compared to using AbstractBehavior this factory is a more functional style of defining the Behavior. Processing the next message results in a new behavior that can potentially be different from this one. State is maintained by returning a new behavior that holds the new immutable state.

但是如何在Behaviors.receiveMessage中实现生命周期信号呢?

这是文档 https://doc.akka.io/api/akka/current/akka/actor/typed/scaladsl/Behaviors 的链接$.html#receiveMessageT:akka.actor.typed.scaladsl.Behaviors.Receive[T]

最佳答案

因为 receiveMessage[A] 只能匹配符合类型 A 的消息,并且您无法声明类型 A > 其中包括 PostStop 等系统消息。相反,Akka-Typed 有一个专用的 receiveSignal

根据您的示例,您已经通过 Behavior.setup 捕获共享上下文,您可以将 receiveSignal 链接到消息行为以成为同一行为的一部分:

Behaviors.setup { context =>
val greeter = context.spawn(HelloWorld.greeter, "greeter")

Behaviors.receiveMessage { message =>
val replyTo = context.spawn(HelloWorldBot.bot(greetingCounter = 0, max = 3), message.name)
greeter ! HelloWorld.Greet(message.name, replyTo)
Behaviors.same
}.receiveSignal {
case (context, PostStop) =>
context.log.info("behavior stopped")
Behaviors.same
}

关于scala - 如何使用Behavior.receiveMessage处理生命周期信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com