在 Akka Typed 中向父 actor 发送消息 [英] Send message to parent actor in Akka Typed

查看:35
本文介绍了在 Akka Typed 中向父 actor 发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题是不言自明的,我希望能够向父actor发送消息(意思是我想要父actor的ActorRef).在 Akka Classic(无类型)中,可以通过以下方式从子角色的 ActorContext 获取父角色的 ActorRef:

Title is self-explanatory, I want to be able to send a message to a parent actor (meaning I want parent's ActorRef). In Akka Classic (untyped), the ActorRef for a parent actor can be obtained from the child's ActorContext via:

context.parent

(例如,参见 这个问题(在 Java 中)).

然而,Akka Typed 中的 akka.actor.typed.scaladsl.ActorContext 没有为父级公开 ActorRef.在 Scala 中是否有一种惯用的方法来为父演员获取 ActorRef?

However, the akka.actor.typed.scaladsl.ActorContext in Akka Typed does not expose an ActorRef for the parent. Is there an idiomatic means in Scala to obtain an ActorRef for the parent actor?

推荐答案

如果您使用的是类型化 Akka,则唯一可以包含所有可能父角色的 ActorRef 的 [Scala] 类型是 ActorRef[Nothing],它是一个 ActorRef,你不能向它发送消息,所以它的效用有限.

If you're in typed Akka, the only [Scala] type that could encompass ActorRefs of all possible parent actors is ActorRef[Nothing], which is an ActorRef you can't send messages to, so that's of limited utility.

至少在经典 API 存在期间:

At least for as long as the classic APIs exist:

import akka.actor.typed.scaladsl.adapter._

type ClassicActorRef = akka.actor.ActorRef

val parentActorRef = context.toClassic.parent

这将是一个无类型的ActorRef,即您可以自由发送父actor永远不会接受的消息.

This will be an untyped ActorRef, i.e. you're free to send messages which the parent actor will never accept.

如果你想要一个对actor父级的类型化引用,你需要在生成子actor时嵌入它,就像你想要一个对当前消息发送者的类型化引用一样,你需要嵌入replyTos 在您的协议中.

If you want a typed reference to an actor's parent, you'll need to embed that when spawning the child actor, just as if you want a typed reference to the sender of the current message you need to embed replyTos in your protocol.

(context.sender 在类型化的 ActorContext 中不存在,原因与 context.parent 不存在相同;复制经典的解决方法context.sender 类似:context.toClassic.sender)

(context.sender is absent in the typed ActorContext for the same reason that context.parent is absent; the workaround for replicating classic context.sender is analogous: context.toClassic.sender)

这篇关于在 Akka Typed 中向父 actor 发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆