EntityTypeKey identifies a category of sharded Akka entities. Together with an entity ID string, it forms a cluster-unique identity: separate entity types can reuse the same ID without colliding. The key also lets Cluster Sharding initialize the behavior used for that entity type. section 9.1.2 section 9.2.2
A sharded shipping container
Define a key for the Container command protocol, then initialize sharding with that key. Messages travel in a ShardingEnvelope containing a container ID; if that entity does not yet exist, sharding creates it. The resulting handle is an EntityRef-style destination rather than an ordinary spawned ActorRef. section 9.1.2
Listing 9.1 Container behavior with containerId and TypeKey
object Container {
val typeKey =
EntityTypeKey[Container.Command]("container-type-key") #1
sealed trait Command
final case class AddCargo(cargo: Cargo) extends Command #2
with CborSerializable #2
final case class GetCargos(replyTo: ActorRef[List[Cargo]]) #2
extends Command with CborSerializable #2
def apply(containerId: String): Behavior[Command] = { #3
ready(List())
}
def ready(cargos: List[Cargo]): Behavior[Command] = { #4
Behaviors.receiveMessage[Command] {
case AddCargo(cargo) =>
ready(cargo +: cargos)
case GetCargos(replyTo) =>
replyTo ! cargos
Behaviors.same
}
}
}
This behavior defines a Container EntityTypeKey and uses the container ID as the per-entity constructor input. section 9.1.2
For event-sourced entities, use the key name with the entity ID when constructing a PersistenceId. That pairing prevents persistent-actor collisions when matching IDs appear on different cluster nodes or across different entity types. section 9.2.1 section 9.2.2
object SPContainer {
val typeKey =
EntityTypeKey[SPContainer.Command]("spcontainer-type-key") #1
...
def apply(containerId: String): Behavior[Command] =
EventSourcedBehavior[Command, Event, State](
PersistenceId(typeKey.name, containerId), #1
State(),
commandHandler,
eventHandler)
...
}
This persistent container uses typeKey.name and containerId to build its PersistenceId. section 9.2.2
