2015-10-21 73 views
1

我試圖通過消息訪問特定actor的狀態。我不知道的是我如何檢索演員的狀態。在這裏,我需要訪問Node的state變量state1。我想避免在代碼中使用promise/futures。如果我想要這樣做,我應該如何修改此代碼?通過消息訪問Akka Actor的狀態

class Node extends Actor { 
    val state1:Int = 4 

     def receive = { 
      case getState => { 
      sender ! ??? //How should I send the 'state1' to the sender? 
      } 
     } 
} 

class Master extends Actor { 

    def recieve = { 
    case someCase(node_actor:ActorRef) => { 
     // My aim here is to get the "state1" from node actor into var 's' 
     var s:Int = node_actor ! getState 
    } 
    } 
} 
+0

你會寫你爲什麼要避免使用未來? – ymonad

+0

這是實際執行中的一個限制,它阻止我使用它們。我能夠描述它的最好方式是它超越了特定數量的演員,並且我想盡可能多地使用它。 – user3204064

+0

請注意,您不必將多行'case'放在大括號中,只需在'case'行足夠多後縮進幾行就可以了 – Odomontois

回答

1

演員的設計非常完美,以避免手動處理scala.concurrent.的東西。 只是單獨的請求和響應處理成不同receive箱子:

class Node extends Actor { 
    import Node._ 
    val state1: Int = 4 

    def receive: Receive = { 
    case getState => 
     sender ! State(state1) 

    } 
} 

class Master extends Actor { 
    import Master._ 
    def receive: Receive = { 
    case Action(node) => 
     // My aim here is to get the "state1" from node actor into var 's' 
     node ! Node.GetState 

    case Node.State(state) => 
     // do something with state 
    } 
} 

object Master { 
    case class Action(node: ActorRef) 
} 

object Node { 
    case object GetState 
    case class State(state: Int) 
} 

有時你可能也有一些計算中間值,並且不想要做的事,直到你會得到答案,但不可達也不能接受。所以,你可以靜靜等待在單獨Receive節點響應,同時積攢收到的消息,像這樣:

class Master extends Actor with Stash { 
    import Master._ 
    def receive: Receive = { 
    case Action(node) => 
     val intermediate = scala.util.Random.nextLong() 
     node ! Node.GetState 
     context.become(waitingForState(calc = intermediate), discardOld = false) 
    } 

    def waitingForState(calc: Long): Receive = { 
    case Node.State(state) => 
     // do something with state and calc 
     context.unbecome() 
     unstashAll() 
    case _ => stash() 
    } 
} 
+0

我創建了主演只是爲了讓我的問題更清楚一點,Node是我在實現中唯一的類,並且在這些節點參與者之間發生狀態的通信和傳遞。這個解決方案似乎也適用於此。 – user3204064