常见的是通过Actor的tell方法给另外一个actor发送消息,但是actor 和 future怎么交互,发送消息,如下,
Future<Object> future = Patterns.ask(a, "are you ready?", timeout);
做了一个Future 和 Actor 结合使用的例子,如下,
package com.usoft; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.pattern.Patterns; import akka.util.Timeout; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * Created by liyanxin on 2015/1/8. */ public class HelloFuture { public static class A extends UntypedActor { private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); @Override public void onReceive(Object message) throws Exception { if (message instanceof String) { Thread.sleep(3000); System.out.println(Thread.currentThread().getName() + " sleep end"); System.out.println("接收的消息:" + message); // 返回一个消息 this.getSender().tell("hello world", this.getSelf()); System.out.println("sender path=" + this.getSender().path()); getContext().stop(this.getSelf()); log.info("|||{} has stop", this.getSelf().path()); } } } public static void main(String args[]) throws Exception { System.out.println(Thread.currentThread().getName()); ActorSystem system = ActorSystem.create("mySystem"); ActorRef a = system.actorOf(Props.create(A.class), "helloWorld"); Timeout timeout = new Timeout(Duration.create(5, "seconds")); Future<Object> future = Patterns.ask(a, "are you ready?", timeout); // This will cause the current thread to block and wait for the UntypedActor to ‘complete’ // the Future with it’s reply. // 在这里会阻塞到 Await.result 方法上,但这会导致性能的损失。 String result = (String) Await.result(future, timeout.duration()); System.out.println(result); } }
运行结果,
main
mySystem-akka.actor.default-dispatcher-4 sleep end
接收的消息:are you ready?
hello world
sender path=akka://mySystem/temp/$a
[INFO] [01/08/2015 16:55:11.267] [mySystem-akka.actor.default-dispatcher-4] [akka://mySystem/user/helloWorld] |||akka://mySystem/user/helloWorld has stop
Maven依赖库
<dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor_2.11</artifactId> <version>2.3.8</version> </dependency>
结果是出来了,但是代码是如何工作的,这些细节还是不清楚的。
=========================END=========================
时间: 2024-10-07 12:31:32