Created
November 6, 2014 15:41
-
-
Save antigremlin/f5b75305f4840d8e8ad5 to your computer and use it in GitHub Desktop.
Ask with retry in akka, forwarding back to sender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package spike.app2; | |
import akka.actor.ActorContext; | |
import akka.actor.ActorRef; | |
import akka.actor.Props; | |
import akka.actor.ReceiveTimeout; | |
import akka.actor.UntypedActor; | |
import akka.dispatch.Futures; | |
import akka.pattern.AskTimeoutException; | |
import scala.concurrent.Future; | |
import scala.concurrent.Promise; | |
import scala.concurrent.duration.Duration; | |
public class Patterns2 { | |
public static void tellRetry(ActorContext context, ActorRef target, Object msg, | |
ActorRef sender, Duration duration, int retries) { | |
context.actorOf(Props.create(RetryActor.class, target, msg, duration, retries, sender)); | |
} | |
static class RetryActor extends UntypedActor { | |
private final ActorRef sender; | |
private final ActorRef target; | |
private final Object msg; | |
private final Duration duration; | |
private int retries; | |
RetryActor(ActorRef target, Object msg, Duration duration, int retries, ActorRef sender) { | |
this.sender = sender; | |
this.target = target; | |
this.msg = msg; | |
this.duration = duration; | |
this.retries = retries; | |
} | |
@Override public void preStart() { | |
getContext().setReceiveTimeout(duration); | |
target.tell(msg, getSelf()); | |
} | |
@Override public void onReceive(Object rmsg) { | |
if (rmsg instanceof ReceiveTimeout) { | |
if (retries > 0) { | |
target.tell(msg, getSelf()); | |
retries--; | |
} else { | |
sender.tell(new AskTimeoutException(""), ActorRef.noSender()); | |
getContext().stop(getSelf()); | |
} | |
} else { | |
sender.forward(rmsg, getContext()); | |
getContext().stop(getSelf()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In fact: retries + 1 (first isn't counted)