Akka Actor_Future的使用

Akka Actor_Future的使用java


常见的是经过Actor的tell方法给另一个actor发送消息,可是actor 和 future怎么交互,发送消息,以下,ide

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);
    }

}

运行结果,this

mainspa

mySystem-akka.actor.default-dispatcher-4 sleep endscala

接收的消息:are you ready?code

hello worldxml

sender path=akka://mySystem/temp/$aget

[INFO] [01/08/2015 16:55:11.267] [mySystem-akka.actor.default-dispatcher-4] [akka://mySystem/user/helloWorld] |||akka://mySystem/user/helloWorld has stopit


Maven依赖库

<dependency>
    <groupId>com.typesafe.akka</groupId>
    <artifactId>akka-actor_2.11</artifactId>
    <version>2.3.8</version>
</dependency>

结果是出来了,可是代码是如何工做的,这些细节仍是不清楚的。

===============END===============

相关文章
相关标签/搜索