我需要对akka actor进行重试,以增加重试之间的时间和最大重试限制。 为此,我尝试使用akka提供的BackOffSupervisor模式。问题是,根据我的测试,退避策略和重试限制似乎不起作用。还是问题出在测试中?
测试如下:
一个简单的actor在前5条消息中引发异常
class SomeActor extends AbstractActor {
private static int messageCounter = 0;
//return the message to sender
@Override
public void preRestart(final Throwable reason, final Optional<Object> message) {
getSelf().tell(message.get(), getSender());
}
@Override
public Receive createReceive() {
return receiveBuilder()
.matchEquals("hello", message -> {
messageCounter++;
getSender().tell("response", getSelf());
//Throw Exception at the first 5 messages
if (messageCounter < 5) {
throw new Exception();
}
})
.build();
}
}
BackOffSupervisor配置
private ActorRef createSupervisedActor(Class<? extends Actor> actorClass) {
final Props someActorProps = Props.create(actorClass);
final Props supervisorProps = BackoffSupervisor.props(
Backoff.onStop(
someActorProps, //actor to be supervised
"someActor",
Duration.ofSeconds(10), //min back-off time
Duration.ofMinutes(2), // max back-off time
0.2, // back-off increase factor
10) // max retry limit
.withSupervisorStrategy(
new OneForOneStrategy(
DeciderBuilder
.match(Exception.class, e -> SupervisorStrategy.restart())
.matchAny(o -> SupervisorStrategy.escalate())
.build())
)
);
return testSystem.actorOf(supervisorProps);
}
测试方法
@Test
public void test() {
new TestKit(testSystem) {{
ActorRef actorRef = createSupervisedActor(SomeActor.class);
actorRef.tell("hello", getRef());
//Expect 5 responses in 1 second
receiveN(5, Duration.ofSeconds(1));
}};
}
测试完成得太快。在不到一秒钟的时间内,从BackoffSupervisor的配置中,我预计至少需要50秒钟以上的时间。
答案 0 :(得分:0)
该问题是由于以下原因:
在子actor(在我的情况下为someActor)中引发异常不是由Backoff.onStop处理的,因此由正常的默认监督处理,这意味着立即重启。 -GHC manual