Akka Remote Actor_簡單示例二java
在上一篇文章中,http://my.oschina.net/xinxingegeya/blog/369445 tcp
使用Patterns.ask方法來與remote actor交互,還有沒有另外一種方式與remote actor交互?那就是使用remote actor path,獲得ActorSelection,從而和remote actor交互。ide
那麼先來了解一下remote actor path的構成,以下,this
akka.<protocol>://<actorsystemname>@<hostname>:<port>/<actor path>
那麼有上篇文章中remote actor的配置可知,其remote actor path爲:
spa
akka.tcp://CalculatorWorkerSystem@127.0.0.1 :2552/user/CalculatorActor.net
示例代碼以下,code
package com.usoft9; import akka.actor.ActorSelection; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import com.typesafe.config.ConfigFactory; /** * Created by liyanxin on 2015/1/19. */ public class RemoteActorSelectionDemo { public static class HandlerResult extends UntypedActor { @Override public void preStart() throws Exception { ActorSelection selection = this.getContext().actorSelection( "akka.tcp://CalculatorWorkerSystem@127.0.0.1:8989/user/CalculatorActor"); selection.tell(new Op.Add(1, 2), this.getSelf()); } @Override public void onReceive(Object message) throws Exception { if (message instanceof Op.AddResult) { System.out.println("add result=" + ((Op.AddResult) message).getResult()); } else if (message instanceof Op.SubtractResult) { System.out.println("subtract result=" + ((Op.SubtractResult) message).getResult()); } else if (message instanceof Op.MultiplicationResult) { System.out.println("multiply result=" + ((Op.MultiplicationResult) message).getResult()); } else if (message instanceof Op.DivisionResult) { System.out.println("divide result=" + ((Op.DivisionResult) message).getResult()); } } } public static void main(String args[]) { //不使用默認的配置,而是選擇加載選定的remote actor配置 final ActorSystem system = ActorSystem.create("CalculatorWorkerSystem", ConfigFactory.load(("usoft9/calculator"))); //初始化遠程actor system.actorOf(Props.create(CalculatorActor.class), "CalculatorActor"); System.out.println("Started CalculatorWorkerSystem"); //初始化本地的Actor final ActorSystem localSystem = ActorSystem.create("localSystem"); localSystem.actorOf(Props.create(HandlerResult.class), "handlerResult"); } }
運行結果,blog
[INFO] [01/19/2015 19:43:12.184] [main] [Remoting] Starting remotingip
[INFO] [01/19/2015 19:43:12.918] [main] [Remoting] Remoting started; listening on addresses :[akka.tcp://CalculatorWorkerSystem@127.0.0.1:8989]rem
[INFO] [01/19/2015 19:43:12.920] [main] [Remoting] Remoting now listens on addresses: [akka.tcp://CalculatorWorkerSystem@127.0.0.1:8989]
Started CalculatorWorkerSystem
[INFO] [01/19/2015 19:43:12.973] [main] [Remoting] Starting remoting
[INFO] [01/19/2015 19:43:13.021] [main] [Remoting] Remoting started; listening on addresses :[akka.tcp://localSystem@127.0.0.1:2552]
[INFO] [01/19/2015 19:43:13.022] [main] [Remoting] Remoting now listens on addresses: [akka.tcp://localSystem@127.0.0.1:2552]
Calculating 1 + 2
add result=3
===================END===================