我正在尝试使用Akka实现具有重试语义的作业。如果一个worker在其工作期间失败(抛出异常),除了重新启动它之外,我想重新提交它正在处理的工作。
我正在尝试的方法是一个自定义主管,但我无法让它在失败时重启工作者。例如使用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);
}
}
知道我做错了吗?
谢谢!
答案 0 :(得分: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.");
}
我没有收到注释掉的任何编译错误。