首页 > 代码库 > Akka Actor_Future的使用
Akka Actor_Future的使用
Akka Actor_Future的使用
常见的是通过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=========================
Akka Actor_Future的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。