akka乒乓球不起作用

时间:2017-07-12 12:19:06

标签: java akka

我希望每隔一秒使用akka调用PingPong个演员。

此代码无效

我想要这个生命周期

TestMain - > ping - >乒乓球 - > ping - >乒乓..

public class TestMain {
    public static void main(String[] args){
        ActorSystem actorSystem = ActorSystem.create("TestActorSystem");
        ActorRef ping = actorSystem.actorOf(Props.create(PingActor.class), "pingActor");
        ping.tell("start", ActorRef.noSender());
    }
}


public class PingActor extends AbstractActor{

    private static Logger log = LoggerFactory.getLogger(PingActor.class);
    private ActorRef pong;

    @Override
    public void preStart() throws Exception {
        this.pong = getContext().actorOf(Props.create(PongActor.class, getSelf()), "pongActor");
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
            .match(PingCallTell.class, this::tell)
            .matchAny(this::unhandled)
            .build();
    }

    public class PingCallTell{}

    private void tell(PingCallTell call) throws Exception{
        log.info("Ping received..");
        pong.tell("ping", getSelf());
    }
}

public class PongActor extends AbstractActor{

    private ActorRef ping;

    public PongActor(ActorRef ping) { 
        this.ping = ping;
    }

    //same PingActor createReceive() 

    private void tell(PongCallTell call) throws Exception {
        log.info("Pong received..");
        ping.tell("pong", getSelf()); 
        Thread.sleep(1000);
    }
}

1 个答案:

答案 0 :(得分:0)

我尽快在Scala中尝试了

object PingPong {
  def main(args: Array[String]): Unit = {
    val actorSystem = ActorSystem.create("PingPongSys")
    val pingPongActor = actorSystem.actorOf(Props[PingPongActor])
    pingPongActor ! Ping
  }
}

class PingPongActor extends Actor {
  override def receive: Receive = {
    case Ping =>
      println("Ping ...")
      Thread.sleep(1000)
      self ! Pong
    case Pong =>
      println("Pong ......")
      Thread.sleep(1000)
      self ! Ping
    case _ =>
      println("Foul !!")
  }
}

输出看起来像

Ping ...
Pong ......
Ping ...
Pong ......
Ping ...
Pong ......
相关问题