Akka actor无法向自己发送PoisonPill消息

3

Java/Akka here. I have the following actor:

public class MyActor extends AbstractActor {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    public MyActor() {
        super();
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
            .match(Init.class, init -> {
                log.info("Sending myself a Poison Pill...");
                self().tell(PoisonPill.getInstance(), self());
            }).match(PoisonPill.class, poisonPill -> {
                log.info("Got the Poison Pill...");
                context().system().terminate();
            }).build();
    }
}

当接收到一个Init消息时,我看到以下日志记录:
Sending myself a Poison Pill...

但我从未看到:

Got the Poison Pill...

此外,该应用程序只是停留在那里,无法按预期关闭。我在使用 self().tell(PoisonPill.getInstance(), self()) 时是否有什么问题,阻止它接收消息并关闭?
1个回答

5
日志消息未出现是因为 PoisonPill 是一个AutoReceivedMessageAutoReceivedMessage 是 Akka 内部处理的一种特殊消息,不应在用户代码中进行模式匹配。

一种关闭演员系统的方法是覆盖演员的 postStop() 方法:

@Override
public Receive createReceive() {
  return receiveBuilder()
    .match(Init.class, init -> {
      log.info("Sending myself a Poison Pill...");
      self().tell(PoisonPill.getInstance(), ActorRef.noSender());
    })
    .build();
}

@Override
public void postStop() {
  getContext().getSystem().terminate();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接