问题
I have 1000 orders and I want to create an actor for each unique orderid. What would be the best way to safely create these actors while guaranteeing that I only have one per unique orderid?
I have tried to first use ActorSelection, then if I can't find an actor with that id, I use ActorOf to create a new one, but when starting batches of these I will get a lot of ActorNotFoundException and when I then try to use ActorOf it fails with InvalidActorNameException.
Example:
try
{
actorRef = await actorSelection.ResolveOne(TimeSpan.FromMilliseconds(3000));
}
catch (ActorNotFoundException)
{
actorRef = Actor.EwmsActorSystem.ActorOf<T>(actorId);
}
回答1:
You should use the Entity Per Child Pattern, i.e. have an actor that spawns child actors per entity ID. You can view an example in the World Crawler sample.
In a nutshell, it should look something like this:
var child = Context.Child(entityId.ToString());
if (child == ActorRefs.Nobody)
child = Context.ActorOf(...); // spawn child actor here
child.Tell(message);
It is also good practice to set a ReceiveTimeout on the child actors, to kill them off when they have been idle for a period of time.
来源:https://stackoverflow.com/questions/40115997/what-is-the-correct-way-to-resolve-an-actor