I don't understand how ID's are assign when you create a new actor in a ShardRegion, I was looking through this example
If someone has a more clearer example that would be great.
I don't understand how ID's are assign when you create a new actor in a ShardRegion, I was looking through this example
If someone has a more clearer example that would be great.
All messages targeting sharded actors (entities) must come through the shard region responsible for the givent type of the entity. A shard region can be initialized like this:
var sharding = ClusterSharding.Get(system);
var shardRegion = sharding.Start(
typeName: nameof(MyActor),
entityProps: Props.Create<MyActor>(), // the Props used to create entities
settings: ClusterShardingSettings.Create(system),
messageExtractor: messageExtractor
);
In order to correctly route messages to entities, shard region must be able to extract the shard-id and entity-id of that entity and a shard, it belongs to. This is a job of a messageExtractor
object (it must implement IMessageExtractor
interface).
A common pattern here is to create a dedicated envelope used to route the actual messages to entities. Below you can see an example - shard id is not provided explicitly, instead it's calculated from the hash of the entity id modulo maximum number of shards (this value, once picked, must never change).
public sealed class ShardEnvelope
{
public readonly string EntityId;
public readonly object Payload;
public ShardEnvelope(string entityId, object payload)
{
EntityId = entityId;
Payload = payload;
}
}
public sealed class MessageExtractor : HashCodeMessageExtractor
{
public MessageExtractor(int maxNumberOfShards) : base(maxNumberOfShards) { }
public override string EntityId(object message) =>
(message as ShardEnvelope)?.EntityId;
public override object EntityMessage(object message) =>
(message as ShardEnvelope)?.Payload;
}
Now, while entities lifecycle is fully managed by cluster sharding and their actual localization within a cluster may change over time (due to rebalancing), their relative path inside the given cluster node always stays the same, and it conforms to the following pattern:
/user/sharding/<typeName>/<shard-id>/<entity-id>
It means that, if you want to extract entity-id and shard-id of your current actor, you can do that directly from actor's path:
var entityId = Self.Path.Name;
var shardId = Self.Path.Parent.Name;