如何对Akka actor系统进行阻塞/同步调用?

sme*_*eeb 2 java actor akka

这里是Akka 2.4.1 Java API.我现在没有足够的带宽来学习Scala,所以我想这里的代码示例也使用Java API.

我有一个ActorSystem充满异步演员的存在,并且工作得非常好.我现在需要在同步上下文中重用这个actor系统,如下所示:

// Groovy pseudo-code; NOT inside the actor system here!
ComputationRequest request = new ComputationRequest(1, 7, true)
MasterActor master = actorSystem.get(...)
ComputationResult result = actorSystem.tell(master, request)
Run Code Online (Sandbox Code Playgroud)

在Akka的文档中没有任何地方我看到一个明确的例子,即将动画发送到演员系统(从外部),然后检索结果.我可以Futures在这里使用吗?在Akka(代码示例)中处理此模式的标准方法是什么?

knu*_*ker 11

还有就是图案你想要做什么.它希望目标tell参与者通过它"返回"响应getSender().你会得到一个Future响应,并可以使用它(阻止,如果你必须).

import akka.dispatch.*;
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
import scala.concurrent.Await;
import scala.concurrent.Promise;
import akka.util.Timeout;


ComputationRequest request = new ComputationRequest(1, 7, true);
MasterActor master = actorSystem.get(...);

Timeout timeout = new Timeout(Duration.create(5, "seconds"));
Future<Object> future = Patterns.ask(master, request, timeout);
ComputationResult result = (ComputationResult) Await.result(future, timeout.duration());
Run Code Online (Sandbox Code Playgroud)