1 Creating Actors
2 Sending and Receiving Messages
3 Working with Multiple Actors
4 Coordinating Actors
5 Using Typed Actors
6 Typed Actors and Murmurs
7 Mixing Actors and STM
8 Using Transactors
9 Coordinating Typed Actors
10 Remote Actors
11 Limitations of the Actor-Based Model
12 epliogue
replyUnsafe()method 回应消息,不检查发送者
import akka.actor.UntypedActor;
import akka.actor.ActorRef;
import akka.actor.Actors;
import akka.actor.ActorTimeoutException;
public class FortuneTeller extends UntypedActor {
public void onReceive(final Object name) {
getContext().replyUnsafe(String.format("%s you'll rock", name));
}
public static void main(final String[] args) {
final ActorRef fortuneTeller =
Actors.actorOf(FortuneTeller.class).start();
try {
final Object response = fortuneTeller.sendRequestReply("Joe");
System.out.println(response);
} catch(ActorTimeoutException ex) {
System.out.println("Never got a response before timeout");
} finally {
fortuneTeller.stop();
}
}
}
结果
Joe you'll rock
replySafe()method 回应消息,检查发送者
import akka.actor.UntypedActor;
import akka.actor.Actors;
import akka.actor.ActorRef;
import akka.actor.ActorTimeoutException;
public class FortuneTeller extends UntypedActor {
public void onReceive(final Object name) {
if(getContext().replySafe(String.format("%s you'll rock", name)))
System.out.println("Message sent for " + name);
else
System.out.println("Sender not found for " + name);
}
public static void main(final String[] args) {
final ActorRef fortuneTeller =
Actors.actorOf(FortuneTeller.class).start();
try {
fortuneTeller.sendOneWay("Bill");
final Object response = fortuneTeller.sendRequestReply("Joe");
System.out.println(response);
} catch(ActorTimeoutException ex) {
System.out.println("Never got a response before timeout");
} finally {
fortuneTeller.stop();
}
}
}
结果
Sender not found for Bill
Message sent for Joe
Joe you'll rock
分析
The call to sendRequestReply() blocks while waiting for a response, but the call to sendOneWay() is nonblocking and yields no response. If we want to receive a response but don’t want to wait for it, we can use the more elaborate method sendRequestReplyFuture(), which will return a Future object. We can go
about doing work until we want the response, at which time we can either block or query the future object to see whether a response is available. Similarly, on the side of the actor, we can get the senderFuture from the context reference and communicate through that right away or later when we have a response ready.
It is quite convenient that Akka passes the sender references under the covers when it sends a message. This eliminates the need to pass the sender explicitly as part of the message and removes so much noise and effort in the code.