如何将参与者消息限制为特定类型? [英] How to restrict actor messages to specific types?

查看:83
本文介绍了如何将参与者消息限制为特定类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Akka 中,除了使用类型化的参与者 API之外,还有一种方法可以将消息限制为特定静态类型的参与者

In Akka, is there a way to restrict messages to actors to be of a specific static type other than using the "Typed Actor" APIs that use an RPC style programming model?

我可以在Akka中使用消息传递样式,而不会在角色边界处放弃静态类型安全性吗?

Can I use the message passing style with Akka without throwing away static type safety at the actor boundaries?

例如,我想使用如下代码:

For example, I'd like to use code like this:

sealed abstract class FooMessage
case object Foo extends FooMessage
case object Bar extends FooMessage

class FooActor extends Actor[FooMessage] {
  def receive = {
    case Foo => () // OK

    // Would raise a compiler error:
    // case s: String => error("Can't happen, String is not a subtype of FooMessage") 

  }
}

val fooActor = actorOf[FooActor]
fooActor ! Foo // OK

// Won't compile:
fooActor ! "Hello"

也许有人可能必须扩展某些基本特征或使用诸如选择以允许系统级消息(退出等)。

Perhaps one would have to extend some base trait or have a construct like Either to allow for system level messages (Exit, etc.).

推荐答案

然后,您必须将消息类型编码为Actor引用,这将大大降低ActorRegistry之类的值。

Then you'd have to encode the message type into the Actor ref, which would drastically decrease the value of something like the ActorRegistry.

此外,使用诸如成为(演员模型的基础)之类的强大机制来键入消息,其价值较低。

Also, with powerful mechanics like "become" (which is fundamental to the actor model) typing the messages is less valuable.

由于Akka不会泄漏内存当消息与当前行为不匹配时,发送错误消息给错误参与者的风险就不一样。

Since Akka doesn't leak memory when a message is not matched to the current behavior, there is not the same risk of sending the "wrong" messages to the "wrong" actor.

此外,参与者是本质上是动态的,因此,如果要使其静态化,请使用TypedActor(它不是RPC,就像RPC作为常规actor一样,void方法是!调用,Future返回类型是!!!,其他返回类型基于! !)

Also, Actors are by nature dynamic, so if you want to make them static, use TypedActor (which is not RPC, it's just as RPC as regular actors, void methods are ! calls, Future return type is !!! and other return types are based on !!)

常见做法e是在Actor的伴随对象中声明Actor可以接收哪些消息,这使知道它可以接收的内容变得非常容易。

The common practice is to declare what messages an Actor can receive in the companion object of the Actor, which makes it very much easier to know what it can receive.

有帮助吗?

这篇关于如何将参与者消息限制为特定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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