如何在运行时取消订阅Akka日志

时间:2018-02-27 11:55:57

标签: scala akka event-bus

我有自己的Actor,使用配置

订阅Akka日志
loggers = ["path.MyActor"]

MyActor收到日志事件,但我想在运行时停止接收它们。 有没有办法做到这一点? (等获得Akka日志的事件总线)

1 个答案:

答案 0 :(得分:2)

您可以致电system.eventStream取消订阅MyActor。例如:

import akka.event.Logging._

case object UnsubscribeFromLogging

class MyActor extends Actor {
  def receive = {
    case InitializeLogger(_)                        => sender() ! LoggerInitialized
    case Error(cause, logSource, logClass, message) => // ...
    case Warning(logSource, logClass, message)      => // ...
    case Info(logSource, logClass, message)         => // ...
    case Debug(logSource, logClass, message)        => // ...

    case UnsubscribeFromLogging => context.system.eventStream.unsubscribe(self)
  }
}

以上示例使用自定义UnsubscribeFromLogging消息:

val myActor: ActorRef = ??? // reference to MyActor
myActor ! UnsubscribeFromLogging

您可以将MyActor的引用传递给另一个actor的unsubscribe方法:

val myActor: ActorRef = ??? // reference to MyActor
context.system.eventStream.unsubscribe(myActor)

无论哪种方式,您都需要引用MyActor。您可以通过确定MyActor的路径(例如,MyActor打印self.path)并将此路径传递给context.actorSelection来获取此信息。