5

我正在尝试使用Akka实现具有重试语义的作业。如果工作人员在其工作期间失败(引发异常),除了重新启动它之外,我还想重新提交它正在处理的工作。

我正在尝试的方法是自定义主管,但我无法让它在失败时重新启动工作人员。例如,使用 Akka 1.1.3 运行以下代码,您将永远不会看到重新启动消息:

  import akka.actor.ActorRef;
  import akka.actor.UntypedActor;
  import akka.actor.UntypedActorFactory;
  import akka.config.Supervision;

  import static akka.actor.Actors.actorOf;
  import static java.lang.System.out;

  public class Supervisor extends UntypedActor {
      private ActorRef worker;

      public static class Worker extends UntypedActor {
          @Override
          public void onReceive(Object message) {
              throw new RuntimeException("croak");
          }

          public void preRestart(Object reason) {
              out.println("supervisor is restarting me!");
          }

          public void postRestart(Object reason) {
              out.println("supervisor restarted me.");
          }
      }

      public static void main(String[] args) {
          ActorRef supervisor = actorOf(new UntypedActorFactory() {
              public UntypedActor create() {
                  return new Supervisor();
              }
          });

          supervisor.start();
          supervisor.sendOneWay("job");
      }

      @Override
      public void preStart() {
          getContext().setFaultHandler(new Supervision.OneForOneStrategy(
              new Class[]{RuntimeException.class},
              3,
              1000
          ));

          // why doesn't the compiler like this line?
          // worker = actorOf(Worker.class);

          worker = actorOf(new UntypedActorFactory() {
              public UntypedActor create() {
                  return new Worker();
              }
          });

          getContext().startLink(worker);
      }

      @Override
      public void onReceive(Object message) {
          worker.sendOneWay(message);
      }
  }

知道我做错了什么吗?

谢谢!

4

1 回答 1

6

Worker这些是actor中重启方法的正确签名:

    @Override
    public void preRestart(Throwable reason) {
        out.println("supervisor is restarting me!");
    }

    @Override
    public void postRestart(Throwable reason) {
        out.println("supervisor restarted me.");
    }

而且我没有收到注释行的任何编译错误。

于 2011-08-16T02:55:47.477 回答