[英]Check if actor exists in akka cluster
我遇到了一種情況,我需要檢查是否存在特定角色,這可以通過指定角色路徑通過ActorSystem.actorSelection方法完成。
但是,當您的本地節點上存在此類參與者時,此方法可以正常工作。 如果actor系統由多個節點組成,並且actor在另一個節點上,則此方法將告知actor不存在。 如果我提供指定遠程角色系統的字符串,則此方法有效。 但這在actorSelection方法中指定遠程actor-system字符串似乎不是一個好主意,因為集群中的節點可以加入和離開。
def getOrCreate(customerId: String, deviceId: String): Future[ActorRef] = { context.system.actorSelection(s"/user/${customerId}{$deviceId}") ? Identify(deviceId) map { case ActorIdentity(`deviceId`, None) => // create new actor case ActorIdentity(`deviceId`, Some(actor)) => actor } }
當actor存在於本地節點上時,以上代碼可以正常工作,為了檢查actor是否存在於集群中的另一個節點上,我必須執行以下操作:
def getOrCreate(customerId: String, deviceId: String): Future[ActorRef] = { context.system.actorSelection(s"akka.tcp://Relay@node1:3503/user/${customerId}{$deviceId}") ? Identify(deviceId) map { case ActorIdentity(`deviceId`, None) => // create new actor case ActorIdentity(`deviceId`, Some(actor)) => actor } }
有沒有更好的方法來檢查actor是否存在於整個akka集群中,而不僅僅是本地節點?
看起來僅當集群中不存在具有相同標識符的actor時,您才想創建一個actor實例。 為此,我認為最好的方法是使用Akka群集分片,並讓Akka負責創建和分發實例。 這也將負責將任何消息路由到參與者到正確的節點,如果集群大小發生變化等,則將參與者重新分配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.