美文网首页
[翻译]squbs官网之4 运行时生命周期&API

[翻译]squbs官网之4 运行时生命周期&API

作者: 乐言笔记 | 来源:发表于2017-10-20 04:19 被阅读13次

    生命周期确实是基础结构的一个关注。应用程序很少需要接触, 甚至不知道系统的生命周期。系统组件、管理控制台, 或者需要长时间进行初始化并且需要在系统可用之前完全初始化的应用程序组件或actor, 这就必须知道系统生命周期。后者包括缓存控制器、缓存加载器、设备初始化,等等。

    squbs运行时暴露了一下生命周期状态:

    • Starting - squbs启动时的初始化状态。
    • Initializing - Unicomplex已启动。服务启动中。Cubes启动中。等待初始化报告。
    • Active - 准备好工作和服务调用。
    • Failed - Cubes没有正确启动。
    • Stopping - Unicomplex收到GracefulStop消息。终止cube,actor并解绑服务。
    • Stopped - squbs运行停止。Unicomplex已终止。 ActorSystem已终止。

    生命周期挂钩
    多数actor不关心它们什么时候启动或者关闭。然而,可能有一类actor需要执行某些初始化, 然后才能到达接受常规通信的状态。同样地, 某些actor也关心在关闭之前被通知, 在送它们毒丸之前让它们正确地清理。生命周期挂钩正是出于这个原因。

    可以让你的actor注册生命周期事件,通过发送ObtainLifecycleEvents(states: LifecycleState)Unicomplex()*。一旦系统状态改变,你的actor将受到生命周期状态。

    你也可以通过向Unicomplex()发送SystemState获取当前状态。你可以得到上面状态的一种的响应。所有的系统状态继承于org.squbs.unicomplex.LifecycleState,并且都是org.squbs.unicomplex包的一部分,如下所示:

    case object Starting extends LifecycleState
    case object Initializing extends LifecycleState
    case object Active extends LifecycleState
    case object Failed extends LifecycleState
    case object Stopping extends LifecycleState
    case object Stopped extends LifecycleState
    

    启动挂钩
    希望参与初始化的actor 必须在 squbs 元数据META-INF/squbs-meta.conf中注明如下:

    cube-name = org.squbs.bottlecube
    cube-version = "0.0.2"
    squbs-actors = [
      {
        class-name = org.squbs.bottlecube.LyricsDispatcher
        name = lyrics
        with-router = false  # Optional, defaults to false
        init-required = true # Tells squbs we need to wait for this actor to signal they have fully started. Default: false
      }
    

    init-required设置为true的任何actor需要发送Initialized(report)消息给cube监管者(是这些 well known actor的父母actor)。Try[Option[String]]类型的报告允许actor报告初始化的成功或者失败(带有异常信息)。一旦所有的cube初始化成功,squbs将变更为Active状态。这也意味着每个init-required设为true的actor提交了成功信息的Initialized(report)。如果任何一个cube通过Initialization(report)报告了初始化错误,squbs将以Failed状态终结。

    关闭挂钩
    停止actor
    org.squbs.lifecycle.GracefulStopHelper特质让用户获得优雅停止他们actor的代码。你可以在你的actor中混入这个特质,用下面的方法。

    class MyActor extends Actor with GracefulStopHelper {
        ...
    }
    

    该特质提供了一些辅助方法来支持 Squbs 框架中的actor的优雅停止。

    停止超时

    StopTimeout
      /**
       * Duration that the actor needs to finish the graceful stop.
       * Override it for customized timeout and it will be registered to the reaper
       * Default to 5 seconds
       * @return Duration
       */
      def stopTimeout: FiniteDuration =
        FiniteDuration(config.getMilliseconds("default-stop-timeout"), TimeUnit.MILLISECONDS)
    

    你可以重写该方法, 以指示此actor需要执行优雅停止大概多长时间。一旦actor启动, 它将发送 stopTimeout (stopTimeout) 消息给其父。如果您关心此消息, 则可以让父actor处理此消息。

    如果你在actor代码中混入了这个特质,你应当在接收方法中处理GracefulStop消息,因为只有这种情况下你可以挂钩你的代码到执行一个优雅的停止(你不可以对PoisonPill证件自定义行为)。监管者只传播GracefulStop消息给混入了GracefulStopHelper特质的孩子。孩子的实现应当在它们的接收代码中处理这个消息。

    我们还提供了特质中以下2个默认策略。

     /**
       * Default gracefully stop behavior for leaf level actors
       * (Actors only receive the msg as input and send out a result)
       * towards the `GracefulStop` message
       *
       * Simply stop itself
       */
      protected final def defaultLeafActorStop: Unit = {
        log.debug(s"Stopping self")
        context stop self
      }
    
     /**
       * Default gracefully stop behavior for middle level actors
       * (Actors rely on the results of other actors to finish their tasks)
       * towards the `GracefulStop` message
       *
       * Simply propagate the `GracefulStop` message to all actors
       * that should be stop ahead of this actor
       *
       * If some actors failed to respond to the `GracefulStop` message,
       * It will send `PoisonPill` again
       *
       * After all the actors get terminated it stops itself
       */
      protected final def defaultMidActorStop(dependencies: Iterable[ActorRef],
                                              timeout: FiniteDuration = stopTimeout / 2): Unit = {
    
        def stopDependencies(msg: Any) = {
          Future.sequence(dependencies.map(gracefulStop(_, timeout, msg)))
        }
    
        stopDependencies(GracefulStop).onComplete({
          // all dependencies has been terminated successfully
          // stop self
          case Success(result) => log.debug(s"All dependencies was stopped. Stopping self")
            if (context != null) context stop self
    
          // some dependencies are not terminated in the timeout
          // send them PoisonPill again
          case Failure(e) => log.warning(s"Graceful stop failed with $e in $timeout")
            stopDependencies(PoisonPill).onComplete(_ => {
              // don't care at this time
              if (context != null) context stop self
            })
        })
      }
    

    停止squbs扩展
    你可以在扩展关闭里增加自定义行为,通过覆盖org.squbs.lifecycle.ExtensionLifecycleshutdown()方法。请注意, 在所有已安装的扩展中, 此方法将在actor系统终止后执行。如果任何扩展在关闭期间抛出异常, JVM 将以-1退出。

    相关文章

      网友评论

          本文标题:[翻译]squbs官网之4 运行时生命周期&API

          本文链接:https://www.haomeiwen.com/subject/uqrmuxtx.html