以持久方式创建子actor(如果不存在)然后向其分发消息的正确模式是什么?
到目前为止,我们的方法如下-理想情况下,我们将在Persist委托动作(如下所示)中创建子actor,但是我们可以确定在方法返回时将创建IActorRef吗?
public class DispatcherActor : ReceivePersistentActor
{
public static Props Props() => Akka.Actor.Props.Create<DispatcherActor>();
public DispatcherActor()
{
Command<IIdentityCommand>(m =>
{
// Intended that this returns an existing or created child actor...
IActorRef identityActor = GetOrBuildIdentityActor(m);
identityActor.Tell(m);
});
}
private IActorRef GetOrBuildIdentityActor(IIdentityCommand msg) =>
Equals(Context.Child(IdentityActor.Path(msg.IdentityNumber)), ActorRefs.Nobody)
? CreateAndPersistIdentityActor(msg)
: Context.Child(IdentityActor.Path(msg.IdentityNumber));
private IActorRef CreateAndPersistIdentityActor(IIdentityCommand msg)
{
Persist(new IdentityActorCreatedEvent(msg.IdentityNumber), @event =>
{
//Can we get an IActorRef from within the persist delegate?
Context.ActorOf(Context.DI().Props<IdentityActor>(), IdentityActor.Path(@event.IdentityNumber));
});
// Will the Child Actor necessarily have been created when this function returns?
return Context.Child(IdentityActor.Path(msg.IdentityNumber));
}
public override string PersistenceId => Self.Path.Name;
}
}