由于Actor之间都是通过异步消息通信的。当发送一条消息给一个Actor后,通常只能等待Actor的返回。与同步方法不同,在发送异步消息后,接受消息的Actor可能还根本来不及处理你的消息,而调用方就已经返回了。
这种模式与之前提到的Future模式非常相像。不同之处只是在传统的异步调用中,进行的是函数调用,但在这里,发送了一条消息。
public class AskMain {
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create("askdemo", ConfigFactory.load("samplehello.conf"));
ActorRef worker = system.actorOf(Props.create(Worker.class), "worker");
ActorRef printer = system.actorOf(Props.create(Printer.class), "printer");
system.actorOf(Props.create(WatchActor.class, worker), "watcher");
//等待future返回
Future<Object> f = Patterns.ask(worker, 5, 1500);
int re = (int)Await.result(f, Duration.create(6, TimeUnit.SECONDS));
System.out.println("return:" + re);
//直接导向其他Actor,pipe不会等待
f = Patterns.ask(worker, 6, 1500);
Patterns.pipe(f, system.dispatcher()).to(printer);
worker.tell(PoisonPill.getInstance(), ActorRef.noSender());
}
}
上述代码给出了两处在Actor交互中使用Future的例子。
代码使用ask()方法给worker发送消息,消息内容是5,也就说worker会接收到一个Integer消息,值为5。当worker接收到消息后,就可以进行计算处理,并且将结果返回给发送者。当然,这个处理过程需要花费一点时间。
方法ask()不会等待worker处理,会立即返回一个Future对象。代码中,使用Await方法等待worker的返回,接着打印返回结果。
在这种方法中,间接地将一个异步调用转为同步阻塞调用。虽然比较容易理解,但是有些场合可能会出现性能问题。另外一种更为有效的方法是使用pipe()函数。
代码中使用ask()再次询问worker,并传递数值6给worker。接着并不进行等待,而是使用pipe()将这个Future重定向到另外一个称为printer的Actor。pipe()函数不会阻塞程序,会立即返回。
这个printer的实现很简单,只是输出得到的数据:
@Override
public void onReceive(Object msg) throws Exception {
if(msg instanceof Integer) {
System.out.println("Printer:" + msg);
}
if(msg == Msg.DONE) {
log.info("Stop working");
}
if(msg == Msg.CLOSE) {
log.info("I will shutdown");
getSender().tell(Msg.CLOSE, getSelf());
getContext().stop(getSelf());
} else {
unhandled(msg);
}
}
上述代码就是Printer Actor的实现,它会通过pipe()方法得到worker的输出结果,并打印在控制台上。
Worker Actor接收一个整数,并计算它的平方,并给予返回,如下:
@Override
public void onReceive(Object msg) throws Exception {
if(msg instanceof Integer) {
int i = (Integer)msg;
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
getSender().tell(i*i, getSelf());
}
if(msg == Msg.DONE) {
log.info("Stop working");
}
if(msg == Msg.CLOSE) {
log.info("I will shutdown");
getSender().tell(Msg.CLOSE, getSelf());
getContext().stop(getSelf());
} else {
unhandled(msg);
}
}
上述代码模拟了一个耗时的调用,为了更明显地说明ask()和pipe()方法的用途。worker计算了给定数值的平方,并“告诉”请求者。