Akka:在演员系统之外进行沟通?

我有以下驱动程序/主类封装我的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消息FizzBuzz#onCluck(Cluck)它生活在演员系统之外? 我可以像这样提供一个FizzBuzz引用给ChickenCluckDetector

class ChickenCluckDetector extends UntypedActor {
    FizzBuzz fizzBuzz

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

            fizzBuzz.onCluck(cluck)
        }
    }
}

但我有一种感觉,这违反了Akka的最佳实践,可能会导致各种基于并发的问题,尤其是如果只有一个FizzBuzz (有)非演员/驱动程序和一万个ChickenCluckDetector演员。 想法?


如果只有一个FizzBu​​zz(哪里有)非演员/司机,还有一万个ChickenCluckDetector演员

那么最好为所有这些ChickenCluckDetector创建一个共同的父项。 然后,这位家长可以安全地持有对FizzBu​​zz的引用,从他所有的孩子那里接收消息并调用onCluck方法。

向演员以外获取消息的一个选择是问。 在斯卡拉有演员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);
        }
    }

}
链接地址: http://www.djcxy.com/p/25733.html

上一篇: Akka: communicating back outside the actor system?

下一篇: Why do we need attr