第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 |