繁体   English   中英

从观察者中删除演员的最佳方法

[英]Best way to remove actor from its watcher

我用play框架和akka编写websocket游戏。 我尝试实施从其经理中删除播放器的操作。 Player演员通过连接代表玩家状态。

public class Player extends UntypedActor {

    private final String openId;
    private final ActorRef out;

    public Player(String openId, ActorRef out) {
        this.openId = openId;
        this.out = out;
    }

    @Override
    public void preStart() throws Exception {
        Application.clientManager.tell(
          new ClientsManager.PlayerConnectedMessage(openId, self()), self()
        );
    }

    @Override
    public void postStop() throws Exception {
        //may be tell my id here?
    }
}

创建时,玩家从prestart在经理actor中注册。 连接关闭时, Player销毁。 我需要从经理中删除它

public class ClientManager extends UntypedActor {

    private static Map<String, ActorRef> clients = new HashMap<>();

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

        if (message instanceof PlayerConnectedMessage) {
            final PlayerConnectedMessage connectedMessage = (PlayerConnectedMessage) message;
            context().watch(connectedMessage.client);
            clients.put(
              connectedMessage.id,
              connectedMessage.client
            );
        } else if (message instanceof Terminated) {
            final ActorRef toDelete = ((Terminated) message).actor();
            //How remove, i have only ActorRef
            clients.remove(...);
        }
    }

    public static class PlayerConnectedMessage {
        private final String id;
        private final ActorRef client;

        public PlayerConnectedMessage(String id, ActorRef client) {
            this.id = id;
            this.client = client;
        }
    }   
}

在我的体系结构中,我想使用Map<String, ActorRef>存储客户端,其中String -may逻辑中的id。 因此,我无法在“已Terminated消息中删除客户端-我只有ActorRef

可能的解决方案:使用ID将PlayerpostStop Disconnect消息告知管理员,并且不再使用watch

是否有使用“监视”方式的优雅解决方案,或者具有postStop()解决方案也不错。 我担心可能的客户泄漏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM