gpt4 book ai didi

scala - Akka Actor如何仅处理最新消息

转载 作者:行者123 更新时间:2023-12-04 13:19:23 25 4
gpt4 key购买 nike

假设我正在向Actor发送消息,则当它正在处理一条消息时,可能还会出现更多消息。现在,当准备好处理下一条消息时,我希望它仅处理最新的消息,因为先前的消息已过时。我怎样才能最好地做到这一点?

使用scala Actors库,我可以通过首先从发送者进行检查来实现此目的,如下所示:

if (myActor.getState != Runnable)
myActor ! message

但是我不认为我可以在Akka系统中进行这样的测试

最佳答案

无需实现自己的邮箱。完全没有。

删除了很多文本,让这段代码说明了一切:

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

这意味着仅在邮箱中没有较新的工作时才执行工作。

关于scala - Akka Actor如何仅处理最新消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21455681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com