第107讲:Akka中的Future使用代码实战详解学习笔记

107讲:Akka中的Future使用代码实战详解学习笔记

本讲分享akka中消息发送的第二种方式:send and receive

actor发送消息后会等待目标actor的回复

future等待目标actor的回复

actorA ask actorB,future来接收actorB的内容。

接收到future后可以提取出future的内容。

 

import akka.util.Timeout;

public class ActorWithFuture {

  public static class Worker extends UntypedActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().system(),this);

    @Override

    public void onReceive(Object message) throws Exception {  //onReceive方法中接收其他actor发送来的消息。

      if (message instanceof String){

        Thread.sleep(3000);  //worker收到message后睡眠3秒种后再反应

        System.out.println(Thread.currentThread().getName() + "is going to work!!!");

System.out.println("The content of the received message is : " + message);

this.getSender().tell("Power comes from LOVE !",this.getSelf());

//源码:def getSender(): ActorRef = sender

        //final def tell(msg: Any, sender: ActorRef): Unit = this.!(msg)(sender)

System.out.println("The sender's path = " + this.getSender().path());

getContext().stop(this.getSelf());  //停止当前actor

log.info("|||{} has stoped", this.getSelf().path());

/**源码:def getLogger(system: ActorSystem, logSource: AnyRef): LoggingAdapter = {

 *   val (str, clazz) = LogSource.fromAnyRef(logSource, system)

 *   new BusLogging(system.eventStream, str, clazz)

 * }

 */

      }

    }

  }

  public static void main(String args[]) throws Exception {

    System.out.println("The name of current thread is : " + thread.currentThread().getName());

    ActorSystem system = ActorSystem.create("System");  //创建ActorSystem的容器。

    ActorRef worker = system.actorOf(new Props(Worder.class),"WorkerActor");  //创建Worker Actor

    Timeout tineout = new Timeout(Duration.create(5, "seconds"));  //等待超时时间5s,

    Future<Object> future = Patterns.ask(worker, "For free, for everyone, forever, for lovel", timeout);  //通过ask的方式发信息给worker,等待worker的回复

    //Patterns.ask方法接收消息

    String result = (String) Await.result(future, timeout.duration());  //通过Await.result的方法等待future的结果

    System.out.println(result);

  }

}

 

akka的路径有akka://System/temp  akka://System/user

 

以上内容是从王家林老师DT大数据课程第107讲的学习笔记。
DT大数据微信公众账号:DT_Spark  

王家林老师QQ:1740415547 

王家林老师微信号:18610086859
DT大数据梦工厂1至110集scala的所有视频、PPT和代码在百度云盘的链接:http://pan.baidu.com/share/home?uk=4013289088#category/type=0&qq-pf-to=pcqq.group

 

第107讲视频网站地址:

6

http://v.ku6.com/show/RjSIVgbN0MN1hmVvi3tTAQ...html

51CTO

http://edu.51cto.com/lesson/id-75984.html

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值