创建一个ActorSelection以获取在父actor中创建的ActorRef

时间:2014-01-23 16:10:51

标签: java akka

我有一个带有ParentOrderActor的Akka系统,可以分别收到CreateRead条消息来创建和阅读孩子 - OrderActor

如果我在 "/user/..."路径中创建所有演员,一切顺利:

// Inside the ParentOrderActor ("/user/orders")

// Create in "/user"
getContext().system().actorOf(new Props(OrderActor.class), "ABC");

// Read via an ActorSelection
ActorSelection actorSelection = getContext().system().actorSelection("/user/ABC");

当一切顺利时,日志会显示出来:

ParentOrderActor -> created: Actor[akka://system/user/ABC#1132819541]
ParentOrderActor -> received: Message[name=Read, id=ABC]
ParentOrderActor -> actorSelection: ActorSelection[Actor[akka://system/]/user/ABC]
ParentOrderActor -> for id=Message[name=Read, id=ABC], we retrieved ActorRef: Actor[akka://system/user/ABC#1132819541]

但是在尝试创建并读取ParentOrderActor中的子actor时:

// Inside the ParentOrderActor ("/user/orders")

// Create in "/user/orders"
getContext().actorOf(new Props(OrderActor.class), "ABC");

// Read via an ActorSelection
ActorSelection actorSelection = getContext().actorSelection("ABC");

正在打印:

ParentOrderActor -> created: Actor[akka://system/user/orders/$a/ABC#-436492577]
ParentOrderActor -> received: Message[name=Read, id=ABC]
ParentOrderActor -> actorSelection: ActorSelection[Actor[akka://system/user/orders/$a#478613574]/ABC]
Oops: java.util.concurrent.TimeoutException: Futures timed out after [2 seconds]
ParentOrderActor -> for id=Message[name=Read, id=ABC], we retrieved ActorRef: null

我在actorSelection(...)尝试了所有类型的路径,但ActorRef始终是null

为了完整起见,这里有一个简短的SSCCE,演示了上述内容:

public class Main {

    private static boolean createChildrenInUser = false;
    private static LoggingAdapter log;

    static abstract class Message {

        final String id;

        Message(String id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Message[name=" + getClass().getSimpleName() + ", id=" + id + "]";
        }
    }

    static class Create extends Message {
        Create(String id) {
            super(id);
        }
    }

    static class Read extends Message {
        Read(String id) {
            super(id);
        }
    }

    static class ParentOrderActor extends UntypedActor {

        @Override
        public void preStart() {
            log.debug("ParentOrderActor -> starting...");
        }

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

            log.debug("ParentOrderActor -> received: {}", message);

            if(message instanceof Create) {
                if(createChildrenInUser) {
                    // Create an Actor in the root context ("/user/id").
                    ActorRef created = getContext().system().actorOf(new Props(OrderActor.class), ((Create)message).id);
                    log.debug("ParentOrderActor -> created: {}", created);
                }
                else {
                    // Create an Actor in this ParentOrderActor's context ("/user/orders/id")
                    ActorRef created = getContext().actorOf(new Props(OrderActor.class), ((Create)message).id);
                    log.debug("ParentOrderActor -> created: {}", created);
                }
            }
            else if(message instanceof Read) {
                ActorRef ref = select((Message)message);
                log.debug("ParentOrderActor -> for id={}, we retrieved ActorRef: {}", message, ref);
                getContext().system().shutdown();
            }
            else {
                unhandled(message);
            }
        }

        private ActorRef select(Message message) {
            try {
                ActorSelection actorSelection;
                if(createChildrenInUser) {
                    // Select the Actor with a certain id in the root context ("/user/id").
                    actorSelection = getContext().system().actorSelection("/user/" + message.id);
                }
                else {
                    // Create an Actor in this ParentOrderActor's context ("/user/orders/id")
                    actorSelection = getContext().actorSelection(message.id);
                }
                log.debug("ParentOrderActor -> actorSelection: {}", actorSelection);
                Timeout timeout = new Timeout(2, TimeUnit.SECONDS);
                AskableActorSelection askableActorSelection = new AskableActorSelection(actorSelection);
                Future<Object> future = askableActorSelection.ask(new Identify(1), timeout);
                ActorIdentity actorIdentity = (ActorIdentity) Await.result(future, timeout.duration());
                return actorIdentity.getRef();
            }
            catch(Exception e) {
                log.debug("Oops: {}", e);
                return null;
            }
        }
    }

    static class OrderActor extends UntypedActor {

        @Override
        public void preStart() {
            log.debug("OrderActor -> starting...");
        }

        @Override
        public void onReceive(Object message) throws Exception {
            log.debug("OrderActor -> received: {}", message);
            unhandled(message);
        }
    }

    public static void main(String[] args) {

        ActorSystem system = ActorSystem.create("system");

        log = Logging.getLogger(system, Main.class);

        ActorRef orders = system.actorOf(new Props(ParentOrderActor.class).withRouter(new RoundRobinRouter(1)), "orders");

        orders.tell(new Create("ABC"), orders);

        orders.tell(new Read("ABC"), orders);
    }
}

运行上述代码会导致Read返回ActorRef null。将布尔标志createChildrenInUser更改为true将在"/user"内创建子actor,一切顺利。

问题:如何创建ActorSelection并获取ActorRef/user/orders)内创建的演员的ParentOrderActor

1 个答案:

答案 0 :(得分:5)

如果我正确理解您的问题,并且您想要从父actor中加载子actor的最佳方法,那么您可以使用:

getContext().child("ABC")

这将返回scala.Option<ActorRef>而不是ActorSelection,因此如果您想要使用通配符查找多个子项并向其发送所有消息,则此方法将无效。