我正在尝试向一些现有演员发布消息,例如下面的节目,但可能有机会引用非现有演员,我想在发布消息之前知道。提前致谢
actor = getContext().actorFor("actorSystem/user/" + nameOfActor);
actor.tell("message",getSelf());
您可以在发送实际消息之前向他们发送识别消息。所有参与者都理解它并且应该用 回复Self()
。或者使用resolveOne
方法:
您可以使用 ActorSelection 的 resolveOne 方法为 ActorSelection 获取 ActorRef。如果存在这样的 Actor,它会返回匹配的 ActorRef 的 Future。如果不存在这样的参与者或识别未在提供的超时内完成,则以失败 [[akka.actor.ActorNotFound]] 完成。
知道一个演员是否活着(没有 DeathWatch)的唯一可能方法是接收来自它的消息。这只能证明演员在某个时间点还活着(当它发送消息时)。
实际上我需要处理收到的每条消息,如果一个演员不存在,那么该消息必须单独处理,我使用 Deadletter 实现来实现
final ActorRef actor = actorSystem.actorOf(new Props(DeadLetterHandlerActor.class));
actorSystem.eventStream().subscribe(actor, DeadLetter.class);
以下是我如何实现使用 DeadLettersHandler 演员来处理 DeadLetters 的代码片段
public class MyActor extends UntypedActor
{
@Override
public void onReceive(Object message) throws Exception
{
System.out.println("MyActor received : "+message.toString());
}
}
public class DeadLettersHandler extends UntypedActor
{
public void onReceive(Object deadLetter) throws Exception
{
System.out.println("DeadLettersHandler received : "+deadLetter.toString());
}
}
public class DeadLetterTest
{
public static void main(String[] args)
{
ActorSystem MyActorSystem = ActorSystem.create("MyActorSystem");
ActorRef existingActor = MyActorSystem.actorOf(Props.create(MyActor.class),"ExistingActor");
ActorRef DLH = MyActorSystem.actorOf(Props.create(DeadLettersHandler.class), "DeadLetterHandler");
MyActorSystem.eventStream().subscribe(DLH, DeadLetter.class);
ActorSelection nonExist = MyActorSystem.actorSelection("akka://user/MyActorSystem/NonExistingActor");
existingActor.tell("Hello Akka", existingActor);
nonExist.tell("Hello Akka", DLH);
MyActorSystem.shutdown();
}
}
output:
MyActor received : Hello Akka
DeadLettersHandler received : DeadLetter(Hello Akka,Actor[akka://MyActorSystem/user/DeadLetterHandler#-3707992],Actor[akka://MyActorSystem/deadLetters])
[INFO] [10/10/2013 15:43:43.343] [MyActorSystem-akka.actor.default-dispatcher-6] [akka://MyActorSystem/deadLetters] Message [java.lang.String] from Actor[akka://MyActorSystem/user/DeadLetterHandler#-3707992] to Actor[akka://MyActorSystem/deadLetters] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.