【发布时间】:2021-01-30 09:24:36
【问题描述】:
我目前正在考虑让两个不同的持久性参与者相互通信。特别是:
Given an Actor A exists
When an Actor B is spawned
Then Actor B must have a reference to Actor A
And Actor B must be able to continuously send messages to Actor A even after relocation
我知道有两种选择:
// With an EntityRef
val counterOne: EntityRef[Counter.Command] = sharding.entityRefFor(TypeKey, "counter-1")
counterOne ! Counter.Increment
// Entity id is specified via an `ShardingEnvelope`
shardRegion ! ShardingEnvelope("counter-1", Counter.Increment)
第二个选项似乎是一个不错的选择,因为我将把对实体的实际引用的解析委托给 Akka。我可能只需要在实例化时将一些包装函数传递给我的 Actor。例如
val shardRegionA: ActorRef[ShardingEnvelope[Counter.Command]] =
sharding.init(Entity(TypeA)(createBehavior = entityContext => A()))
def delegate_A(id,message) = {
shardRegionA ! ShardingEnvelope(id,message)
}
val shardRegionB: ActorRef[ShardingEnvelope[Counter.Command]] =
sharding.init(Entity(TypeB)(createBehavior = entityContext => B(delegate_A)))
--------
object B {
def apply(delegate) = {
...somewhere inside the state...
delegate("some_id_of_A", Message("Hello"))
...somewhere inside the state...
}
}
但是,我还想了解第一个选项是否更简单,因为 EntityRef 可能在状态/事件中安全持久化。
object B {
def apply(entityRefA : EntityRef[A]) = {
EventSourcedBehavior[...](
emptyState = State(entityRefA)
)
}
}
有人对此有任何见解吗?
【问题讨论】:
标签: akka akka-cluster akka-persistence akka-typed