2014-03-13 19 views
2

在Akka Actor中,我想向父母發送消息,但前提是它不是用戶監護人(即僅在Actor不是頂級Actor時)。檢查Actor的父母是否爲User Guardian的最佳方法是什麼?檢查ActorRef是否是用戶監護人

我可以這樣做:

if(context.parent.path.toString != "akka://system/user") { ... } 

但有一種更好的方式?我很想能夠做到像:

if(context.parent != context.system.userGuardian) { ... } 

回答

1

有點棘手,但它的工作原理:

if(context.parent != context.system.asInstanceOf[ExtendedActorSystem].guardian) {...} 
0

你應該能夠做到==對比只要你有給用戶一個參考監護人。這個簡單的例子表明,平等運作正確。所以,我想你可以某處解決用戶的監護人,並使其全球可用,如果你想要做的比較:

object RootGuardianTest extends App{ 
    val system = ActorSystem("test") 
    system.actorOf(Props[ChildActor], "child") 
} 

trait RootComparison{ me:Actor => 

    def initCompare{ 
    val sel = context.system.actorSelection("/user") 
    sel ! Identify() 
    } 

    def checkCompare:Receive = { 
    case ActorIdentity(_, Some(ref)) =>  
     println(s"I am ${self.path}, and my parent is root: ${context.parent == ref}")  
    } 
} 

class ChildActor extends Actor with RootComparison{ 
    val child2 = context.actorOf(Props[Child2Actor], "child2") 
    initCompare 
    def receive = checkCompare 
} 

class Child2Actor extends Actor with RootComparison{ 
    initCompare 
    def receive = checkCompare 
} 

我,我只想簡單地檢查父路徑的name部分,看看它是否是「用戶'如此:

val parentIsUser = context.parent.path.name == "user"