通过消息访问Akka Actor的状态

时间:2015-10-21 06:40:48

标签: scala akka

我正试图通过消息传递来访问特定actor的状态。我不知道的是我如何检索演员的状态。在这里,我需要访问Node的状态变量state1。我想避免在代码中使用promises /期货。如果我想这样做,我应该如何修改此代码?

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
    } 
  }
}

1 个答案:

答案 0 :(得分: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()
  }
}