這是一個很好的使用案例context.become
。
請記住,比Akka actor中的接收塊只是PartialFunction[Any, Unit]
,所以我們可以將它包裝在另一個部分函數中。這與Akka內置的LoggingReceive採用的方法相同。
class TimingReceive(r: Receive, totalTime: Long)(implicit ctx: ActorContext) extends Receive {
def isDefinedAt(o: Any): Boolean = {
r.isDefinedAt(o)
}
def apply(o: Any): Unit = {
val startTime = System.nanoTime
r(o)
val newTotal = totalTime + (System.nanoTime - startTime)
log.debug("Total time so far: " + totalTime + " nanoseconds")
ctx.become(new TimingReceive(r, newTotal))
}
}
object TimingReceive {
def apply(r: Receive)(implicit ctx: ActorContext): Receive = new TimingReceive(r, 0)
}
然後你可以使用它像這樣:
class FooActor extends Actor {
def receive = TimingReceive {
case x: String => println("got " + x)
}
}
每個消息後,演員將記錄至今所花費的時間。當然,如果你想用這個變量做別的事情,你必須適應這個。
這種方法不會測量演員活着的時間,當然只是實際處理消息所花費的時間。如果您的接收功能創造未來,也不會是準確的。