forked from ReactiveDesignPatterns/CodeSamples
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathAskActorWithJava8.java
More file actions
61 lines (49 loc) · 1.48 KB
/
AskActorWithJava8.java
File metadata and controls
61 lines (49 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* Copyright (c) 2018 https://www.reactivedesignpatterns.com/
*
* Copyright (c) 2018 https://rdp.reactiveplatform.xyz/
*
*/
import static akka.pattern.Patterns.ask;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.japi.Creator;
import java.time.Duration;
import java.util.concurrent.CompletionStage;
public class AskActorWithJava8 {
public static class Request {
private final int reqId;
public Request(int reqId) {
this.reqId = reqId;
}
public int getReqId() {
return reqId;
}
}
public static class Response {}
public static class MyActor extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder()
.matchAny((msg) -> getSender().tell(new Response(), getSelf()))
.build();
}
}
public static void processIt(Response response) {
System.out.println(response);
}
private static final ActorSystem ACTOR_SYSTEM = ActorSystem.create();
public static void main(String[] args) {
final ActorRef actorRef =
ACTOR_SYSTEM.actorOf(Props.create(MyActor.class, (Creator<MyActor>) MyActor::new));
final Request request = new Request(1);
final Duration timeout = Duration.ofSeconds(1L);
// #snip
final CompletionStage<Response> future =
ask(actorRef, request, timeout).thenApply(Response.class::cast);
future.thenAccept(AskActorWithJava8::processIt);
// #snip
}
}