猿问

如何检测akka actor终止是由于系统关闭并避免重新启动它

我有一个 Spring 应用程序,它使用一个小型 Akka actor 系统(使用 Java),其中我有一个MasterActor扩展 Akka 的系统AbstractActor,它初始化 aRouter并设置一些 worker actor。它还监视工人的生命周期。我想重启一个 Worker 演员,如果它恰好因为某些原因而死亡Exception。


 public MasterActor(ActorPropsFactory actorPropsFactory) {

    this.actorPropsFactory = actorPropsFactory;


    int workers = Runtime.getRuntime().availableProcessors() - 1;


    List<Routee> routees = Stream.generate(this::createActorRefRoutee).limit(workers).collect(Collectors.toList());


    this.router = new Router(new ConsistentHashingRoutingLogic(getContext().system()), routees);

  }


  private ActorRefRoutee createActorRefRoutee() {

    ActorRef worker = getContext().actorOf(actorPropsFactory.create(getWorkerActorClass()));

    getContext().watch(worker);

    return new ActorRefRoutee(worker);

  }


  private void route(Object message, Supplier<String> routingKeySupplier) {

    String routingKey = routingKeySupplier.get();

    RouterEnvelope envelope = new ConsistentHashingRouter.ConsistentHashableEnvelope(message, routingKey);

    router.route(envelope, getSender());

  }


 @Override

  public Receive createReceive() {

    return receiveBuilder()

        .match(

            EventMessage.class,

            message -> this.route(message, () -> message.getEvent().getId().toString()))

        .match(

            Terminated.class,

            message -> {

              logger.info("WorkerActor {} terminated, restarting", message.getActor());

              // todo: detect whether the system is shutting down before restarting the actor

              router = router.removeRoutee(message.actor())

                             .addRoutee(createActorRefRoutee());

            })

        .build();

  }

我遇到的问题是,如果 Spring 应用程序无法启动。(例如,它无法连接到数据库,或者某些凭据不正确等等),我收到了Terminated所有工作人员的消息,Master actor 尝试启动新的,这也会Terminated立即进入,进入无限循环。


检测这种情况的正确方法是什么?有没有办法让 Master actor 检测到 actor 系统正在关闭,这样 workers 就不会再次重启?


holdtom
浏览 140回答 1
1回答

守着星空守着你

难道你不能只为你的路由器设置一个监督策略,这样你就可以检查导致失败的异常类型吗?这样你也不需要手动重启你的工人。编辑:SupervisorStrategy你这样设置:private static SupervisorStrategy strategy=&nbsp; &nbsp; new OneForOneStrategy(&nbsp; &nbsp; 10,&nbsp; &nbsp; Duration.ofMinutes(1),&nbsp; &nbsp; DeciderBuilder.match(ArithmeticException.class,e->SupervisorStrategy.resume())&nbsp; &nbsp; .match(NullPointerException.class,e->SupervisorStrategy.restart())&nbsp; &nbsp; .match(IllegalArgumentException.class,e->SupervisorStrategy.stop())&nbsp; &nbsp; .matchAny(o->SupervisorStrategy.escalate())&nbsp; &nbsp; .build());final ActorRef router=&nbsp; &nbsp; &nbsp; &nbsp; system.actorOf(&nbsp; &nbsp; &nbsp; &nbsp; new RoundRobinPool(5).withSupervisorStrategy(strategy).props(Props.create(Echo.class)));
随时随地看视频慕课网APP

相关分类

Java
我要回答