actor
生命周期
- preStart()和postStop可用用来初始化和消息处理后清理资源
- preRestart()和postRestop()可用用于异常重启时的一些预操作
Actor创建
ActorRef aggregateActor = getContext().actorOf(Props.create(AggregateActor.class),"AggregateActor");
带构造函数的创建
ActorRef reduceActor = getContext().actorOf(Props.create(ReduceActor.class,aggregateActor).withRouter(new RoundRobinPool(5)),"reduceActor");
异步调用
Future
执行上下文
为了运行回调和操作,Futures 需要有一个ExecutionContext,它与java.util.concurrent.Executor很相像. 如果你在作用域内有一个ActorSystem,它会把自己的派发器用作ExecutionContext,或者你也可以用ExecutionContext伴生对象提供的工厂方法来将Executors和ExecutorServices进行包装,或者甚至创建自己的实例。
final ExecutionContext ec = getContext().system().dispatcher();
转换
sequence和traverse两个辅助方法可以帮助处理更复杂的情况。这两个方法都是用来将T[Future[A]]转换为Future[T[A]]。
Future.sequence将输入的List[Future[Int]]转换为Future[List[Int]]. 这样我们就可以将map直接作用于List[Int],从而得到List的总和。
final Future<Iterable<Object>> aggregate = Futures.sequence(futures,getContext().system().dispatcher());
发送Future到Actor To send the result of a Future to an Actor, you can use the pipe construct:
Patterns.pipe(msg,ec).to(actor);
消息转发
forward message将消息从一个actor路由到另一个actor,用于负载均衡,或者路由。
actor.forward(message, getContext());
终止Actor
- System.shutdown()方法,终止所有actor和actor系统
- 发送poisonPill()消息,它会放入mailbox,只到处理到它,duang,gave over.
- getContext.stop(self)
stop
- Actor stops processing the mailbox messages.
- Actor sends the STOP signal to all the children.
- Actor waits for termination message from all its children.
- Next, Actor starts the self-termination process that involves the following: Invoking the postStop() method Dumping the attached mailbox Publishing the terminated message on DeathWatch Informing the supervisor about self-terminationld
Actors are stopped in the following ways: When the actor system calls the shutdown() method, this technique shuts down all the actors and the actor system. By sending a Poi sonPi l l message to an actor—Poi sonPi l l is like any message that goes and sits in the mailbox of the actor. A Poi sonPi l l message is processed by initiating the shutdown of the actor. By calling context .stop(self) for stopping itself and calling context . stop(chi ld) to stop the child actors.
Killing Actor
- 发送kill()消息,被杀的Actor会发送异常往上传递。
例子
有一个异步调用的例子,用到了Future,转换,Patterns.pipe
参阅:FutureActor