如何实现生命周期PostStop?

时间:2019-06-27 20:12:56

标签: scala akka akka-typed

我有一个演员,实现看起来如下:

  def create(fsm: ActorRef[ServerHealth], cancel: Option[Cancellable]): Behavior[ServerHealthStreamer] =
    Behaviors.setup { context =>
      implicit val system = context.system
      implicit val materializer = ActorMaterializer()
      implicit val dispatcher = materializer.executionContext

      val kafkaServer = system
        .settings
        .config
        .getConfig("kafka")
        .getString("servers")

      val sink: Sink[ServerHealth, NotUsed] = ActorSink.actorRefWithAck[ServerHealth, ServerHealthStreamer, Ack](
        ref = context.self,
        onCompleteMessage = Complete,
        onFailureMessage = Fail.apply,
        messageAdapter = Message.apply,
        onInitMessage = Init.apply,
        ackMessage = Ack)

      val cancel = Source.tick(1.seconds, 15.seconds, NotUsed)
        .flatMapConcat(_ => Source.fromFuture(health(kafkaServer)))
        .map {
          case true =>
            KafkaActive
          case false =>
            KafkaInactive
        }
        .to(sink)
        .run()

      Behaviors.receiveMessage {
        case Init(ackTo) =>
          ackTo ! Ack
          Behaviors.same
        case Message(ackTo, msg) =>
          fsm ! msg
          ackTo ! Ack
          create(fsm, Some(cancel))
        case Complete =>
          Behaviors.same
        case Fail(_) =>
          fsm ! KafkaInactive
          Behaviors.same
      }
    }

如您所见,我正在使用akka类型的输入,并且对实现PostStop生命周期存在疑问。

如何在Akka类型中实现生命周期挂钩?

我要存档的是,当演员收到消息PostStop时,流将被取消。

1 个答案:

答案 0 :(得分:1)

actor lifecycle events”作为“信号”(在本例中为PostStop信号)被告知Akka Typed的演员。