Akka Actor如何仅处理最新消息 [英] Akka Actor how to only process the latest message
问题描述
说我正在向Actor发送消息,当它正在处理一条消息时,可能还会出现更多消息。现在,当准备处理下一条消息时,我希望它仅处理最新的消息,因为先前的消息已过时。我怎样才能最好地做到这一点?
Say I am sending messages to an Actor, when it is processing one message several more messages may arise. Now when it is ready to process the next message I want it to only process the latest message as the previous ones have become obsolete. How can I best achieve this?
使用scala Actors库,首先可以从发件人处进行检查,如下所示:
Using the scala Actors library I was able to achieve this by first checking from my sender as follows:
if (myActor.getState != Runnable)
myActor ! message
但是我不认为我可以在Akka系统中进行这样的测试
But I don't think I can do such a test in the Akka system
推荐答案
无需实现自己的邮箱。
There is no need to implement your own mailbox. At all.
删除了大量文本,并让这段代码说明一切:
Removed a lot of text and let this piece of code speak for itself:
// Either implement "equals" so that every job is unique (by default) or do another comparison in the match.
class Work
case class DoWork(work: Work)
class WorkerActor extends Actor {
// Left as an exercise for the reader, it clearly should do some work.
def perform(work: Work): Unit = ()
def lookingForWork: Receive = {
case w: Work =>
self forward DoWork(w)
context become prepareToDoWork(w)
}
def prepareToDoWork(work: Work): Receive = {
case DoWork(`work`) =>
// No new work, so perform this one
perform(work)
// Now we're ready to look for new work
context become lookingForWork
case DoWork(_) =>
// Discard work that we don't need to do anymore
case w2: Work =>
// Prepare to do this newer work instead
context become prepareToDoWork(w2)
}
//We start out as looking for work
def receive = lookingForWork
}
这意味着仅当没有更新时才执行工作在邮箱中工作。
This means that work will only be performed if there is no newer work in the mailbox.
这篇关于Akka Actor如何仅处理最新消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!