gpt4 book ai didi

java - Akka:在 actor 系统之外进行通信?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:32:12 24 4
gpt4 key购买 nike

我有以下驱动程序/主类封装了我的 Akka 程序:

// Groovy pseudo-code
class FizzBuzz {
ActorSystem actorSystem

static void main(String[] args) {
FizzBuzz d = new FizzBuzz()
d.run()
}

void run() {
Initialize initCmd = new Initialize()
MasterActor master = actorSystem.get(...)

// Tells the entire actor system to initialize itself and start doing stuff.
// ChickenCluckDetector is an actor managed/supervised by MasterActor.
master.tell(initCmd, ...)
}

// Called when a ChickenCluckDetector actor inside the actor system receives
// a 'Cluck' message.
void onChickenGoesCluck(Cluck cluck) {
// Do something
}
}

以及以下 ChickenCluckDetector 参与者:

class ChickenCluckDetector extends UntypedActor {
@Override
void onReceive(Object message) {
if(message instanceof Cluck) {
Cluck cluck = message as Cluck

// Now, how to pass the message safely/properly to FizzBuzz#onCluck?
}
}
}

所以手头的问题是如何安全/正确地将 Cluck 消息传递给 FizzBu​​zz#onCluck(Cluck)外面 actor 系统?可以 提供对ChickenCluckDetectorFizzBu​​zz 引用,如下所示:

class ChickenCluckDetector extends UntypedActor {
FizzBuzz fizzBuzz

@Override
void onReceive(Object message) {
if(message instanceof Cluck) {
Cluck cluck = message as Cluck

fizzBuzz.onCluck(cluck)
}
}
}

但我觉得这违反了 Akka 的最佳实践,并可能导致各种基于并发的问题,特别是如果只有一个 FizzBu​​zz(存在)非 Actor /驱动程序,并且十个千 ChickenCluckDetector Actor 。想法?

最佳答案

if there's only one FizzBuzz (which there is) non-actor/driver, and ten thousand ChickenCluckDetector actors

那么最好为所有这些 ChickenCluckDetectors 创建一个共同的父级。然后,该父级可以安全地持有对 FizzBu​​zz 的引用,接收来自他所有子级的咯咯声并调用 onCluck 方法。

在 actors 之外获取消息的一个选项是询问。在 Scala 中有 actor DSL(添加只是为了完整性)。但我相信您的示例中不需要这些。

public class ChickenCluckMaster extends UntypedActor {

private FizzBuzz fizzBuzz;

public ChickenCluckMaster(FizzBuzz fizzBuzz) {
this.fizzBuzz = fizzBuzz;
}

public void onReceive(Object message) throws Exception {
if (message instanceOf CreateDetector) {
getContext().actorOf(
Props.create(ChickenCluckDetector.class, getSelf); // Create child
} else if (message instanceof Cluck) {
fizzBuzz.onCluck(cluck);
} else {
unhandled(message);
}
}

}

public class ChickenCluckDetector extends UntypedActor {

private ActorRef master;

public ChickenCluckDetector(ActorRef master) {
this.master = master;
}

public void onReceive(Object message) throws Exception {
if (message instanceof Cluck) {
Cluck cluck = (Cluck) message;
master.tell(cluck, getSelf);
} else {
unhandled(message);
}
}

}

关于java - Akka:在 actor 系统之外进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827703/

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