AKKA Inbox收件箱

原由

獲得ActorRef就能夠給actor發送消息,但沒法接收多回復,也不知道actor是否中止java

Inbox收件箱出現就是解決這兩個問題spa

 

示例

package akka.demo.actor

import akka.actor.*
import java.time.Duration

/**
 ** created by tankx
 ** 2019/9/12 與actor 通訊模式ask或tell 沒法支持接收多回復和觀察其它actor的生命週期,因此inbox應用而生
 **/
fun main() {


  val system = ActorSystem.create("box-sys")

  val helloActor = system.actorOf(HelloActor.props("tom"))
  helloActor.tell("hi", ActorRef.noSender())

  val box = Inbox.create(system)
  box.send(helloActor, "how are you!")

  box.watch(helloActor)//監控actor 的生命週期,當actor stop, receive會接收到Terminated消息

  helloActor.tell(PoisonPill.getInstance(), ActorRef.noSender());//毒死actor
  
  while (true) {
    try {

      val receiveObj = box.receive(Duration.ofSeconds(2))//可一直接收actor回的消息
      println("box receive:" + receiveObj)

      if (receiveObj is Terminated) {
        break
      }
    } catch (e: Exception) {
      println(e.message)
    }
  }



  Thread.sleep(2000)
  System.exit(1)

}
相關文章
相關標籤/搜索