Akka演员获得剩余的消息列表

时间:2016-12-02 09:34:43

标签: scala actor

我有一个演员计算强化的东西,理想情况下只有最后的结果才算数。

我希望如果它收到多个相同类型A(data)的消息,则只处理最后一个消息,并丢弃之前的消息。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

自定义邮箱

您可以尝试实现一些包含0或1条消息的自定义邮箱:

import akka.actor.{ActorRef, ActorSystem}
import akka.dispatch._
import com.typesafe.config.Config

class SingleMessageQueue extends MessageQueue {
  var message = Option.empty[Envelope]
  def enqueue(receiver: ActorRef, handle: Envelope) = message = Some(handle)
  def dequeue() = {
    val handle = message.orNull
    message = None
    handle
  }
  def numberOfMessages = message.size
  def hasMessages = message.nonEmpty
  def cleanUp(owner: ActorRef, deadLetters: MessageQueue) = message.foreach(deadLetters.enqueue(owner, _))
}

final case class SingleMessageMailbox() extends MailboxType with ProducesMessageQueue[SingleMessageQueue] {

  def this(settings: ActorSystem.Settings, config: Config) = this()

  override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue = new SingleMessageQueue
}

然后为the mailbox section of the docs

中描述的演员启用它

分裂演员

你可以介绍一对演员。

  • Manager,收到一份工作,只要它现在不能正常工作,就将其重新发送到Worker
  • Worker做实际工作,并在完成后通知经理

示例:

import akka.actor.{Actor, ActorRef, Props}

object Worker {
  case class Job()
  case object JobDone
}

import Worker.{Job, JobDone}

class Worker extends Actor {
  override def receive = {
    case Job() ⇒
      // your long job
      context.parent ! JobDone
  }
}

class Manager extends Actor {
  var nextJob = Option.empty[(Job, ActorRef)]
  val worker = context.actorOf(Props[Worker])

  def working: Receive = {
    case job: Job ⇒ nextJob = Some((job, sender))
    case JobDone ⇒
      nextJob match {
        case Some((job, snd)) ⇒ worker.tell(job, snd)
        case None ⇒ context.become(free)
      }
  }

  def free: Receive = {
    case job: Job ⇒
      worker.tell(job, sender)
      context.become(working)
  }

  override def receive = free
}