Akka演员消息序列

时间:2016-09-15 19:53:33

标签: java akka message

我有以下演员结构

import akka.actor.ActorRef;
import akka.actor.UntypedActor;

public class ExampleActor extends UntypedActor {
    ActorRef worker1;
    ActorRef worker2;

    @Override
public void onReceive(Object msg) throws Exception {


    if (msg instanceof PerformTask) {

        worker1.tell(doTask1, getSelf());
        worker2.tell(doTask2, getSelf());

        // Perform some task with the results of the above two calls

    }
}

}

import akka.actor.UntypedActor;

public class Worker1 extends UntypedActor {

    @Override
    public void onReceive(Object msg) throws Exception {

        if (msg instanceof doTask1) {
            return result1;
        }

    }

}

工人2

import akka.actor.UntypedActor;

public class Worker2 extends UntypedActor {

    @Override
    public void onReceive(Object msg) throws Exception {

        if (msg instanceof doTask2) {
            return result2;
        }

    }

}

如何在ExampleActor执行自己的任务之前确保获得结果1和结果2?

如果我在exampleActor中有单独的消息来接收响应,我该如何将此响应传递给" PefrformTask"动作?

1 个答案:

答案 0 :(得分:0)

您需要开始在ExampleActor中建立状态。当您收到Workers中等待的两个回复中的任何一个时,您需要保存该回复。消息,或者只是消息的相关内容。类似的东西:

if (msg instanceof WorkerTaskResult) {
    results.add((WorkerTaskResult)msg);
}
if(results.size() == number_of_results_expected) {
    //perform whatever I wanted to do on those results from workers
}

results当然是ExampleActor上的非静态字段。

注意:
上面的这个例子非常简单,只是为了让您了解解决方案。有许多事情要注意:ExampleActor重新启动/工人没有产生结果等