Skip to content

Instantly share code, notes, and snippets.

@patriknw
Created December 14, 2019 08:47
Show Gist options
  • Save patriknw/b88ffe57a10b9c1321e32026834b99ce to your computer and use it in GitHub Desktop.
Save patriknw/b88ffe57a10b9c1321e32026834b99ce to your computer and use it in GitHub Desktop.
Methods delegation to actor
package squerer;
import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.Scheduler;
import akka.actor.typed.javadsl.AbstractBehavior;
import akka.actor.typed.javadsl.ActorContext;
import akka.actor.typed.javadsl.AskPattern;
import akka.actor.typed.javadsl.Behaviors;
import akka.actor.typed.javadsl.Receive;
import java.time.Duration;
import java.util.concurrent.CompletionStage;
public interface Squarer {
void squareDontCare(int i); // fire-forget
CompletionStage<Integer> square(int i); // non-blocking send-request-reply
}
class SquarerProxy implements Squarer {
private final ActorRef<SquererImpl.Command> delegate;
private final Scheduler scheduler;
private final Duration askTimeout = Duration.ofSeconds(3);
SquarerProxy(ActorRef<SquererImpl.Command> delegate, Scheduler scheduler) {
this.delegate = delegate;
this.scheduler = scheduler;
}
public void squareDontCare(int i) {
delegate.tell(new SquererImpl.SquereNoReply(i));
}
public CompletionStage<Integer> square(int i) {
CompletionStage<SquererImpl.Result> result =
AskPattern.ask(
delegate, replyTo -> new SquererImpl.Squere(i, replyTo), askTimeout, scheduler);
return result.thenApply(r -> r.y);
}
}
class SquererImpl extends AbstractBehavior<SquererImpl.Command> {
interface Command {}
static class SquereNoReply implements Command {
final int x;
SquereNoReply(int x) {
this.x = x;
}
}
static class Squere implements Command {
final int x;
final ActorRef<Result> replyTo;
Squere(int x, ActorRef<Result> replyTo) {
this.x = x;
this.replyTo = replyTo;
}
}
static class Result {
final int y;
Result(int y) {
this.y = y;
}
}
public static Behavior<Command> create() {
return Behaviors.setup(SquererImpl::new);
}
private SquererImpl(ActorContext<Command> context) {
super(context);
}
@Override
public Receive<Command> createReceive() {
return newReceiveBuilder()
.onMessage(Squere.class, this::onSquere)
.onMessage(SquereNoReply.class, this::onSquereNoReply)
.build();
}
private Behavior<Command> onSquere(Squere command) {
Result result = new Result(command.x * command.x);
command.replyTo.tell(result);
return this;
}
private Behavior<Command> onSquereNoReply(SquereNoReply command) {
System.out.println(command.x * command.x);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment