Search code examples
scalaakkaactor

Where is wrong in my remote actor demo?


I'm trying to send messages to a remote actor, but failed.

My main code is:

RemoteActorDemo.scala

import akka.actor.{Actor, ActorSystem, Props}

object RemoteActorDemo extends App {
  val system = ActorSystem("RemoteActorSystem")
  val actor = system.actorOf(Props[RemoteActor], name = "RemoteActor")
  actor ! "Remote Actor is alive"
}

class RemoteActor extends Actor {
  override def receive: Receive = {
    case msg =>
      println("### RemoteActor received message: " + msg)
      sender ! "Hello from RemoteActor"
  }
}

With application.conf:

akka {
  actor {
    provider = "akka.remote.RemoteActorRefProvider"
  }
  remote {
    enabled-transports = ["akka.remote.netty.tcp"]
    netty.tcp {
      hostname = "127.0.0.1"
      port = 5150
    }
  }
}

And LocalActorDemo.scala:

import akka.actor.{Actor, ActorSystem, Props}

object LocalActorDemo extends App {
  val system = ActorSystem("ActorDemo")

  val localActor = system.actorOf(Props[LocalActor])
  localActor ! "Start"
}

class LocalActor extends Actor {
  val remote = context.actorSelection("akka.tcp://RemoteActorSystem@127.0.0.1:5150/user/RemoteActor")

  override def receive: Receive = {
    case "Start" =>
      println("### LocalActor started")
      remote ! "Hello from LocalActor"
    case msg => println("*** LocalActor receives msg: " + msg)
  }
}

The problem is the local actor can't connect the remote one. It prints in console:

### LocalActor started
[INFO] [10/05/2015 20:57:57.334] [ActorDemo-akka.actor.default-dispatcher-4] [akka://ActorDemo/deadLetters] 
Message [java.lang.String] from Actor[akka://ActorDemo/user/$a#-11944341] to Actor[akka://ActorDemo/deadLetters] 
was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration 
settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.

I'm new to akka, not sure where is wrong.

You can see the demo project here: https://github.com/freewind/remote-actors-demo, you can just clone and run it as "README" describes.


Solution

  • Add an application.conf in your local subproject with content like this:

    akka {
      actor {
        provider = "akka.remote.RemoteActorRefProvider"
      }
      remote {
        enabled-transports = ["akka.remote.netty.tcp"]
        netty.tcp {
          hostname = "127.0.0.1"
          port = 0
        }
      }
    }
    

    As the official document says:

    To enable remote capabilities in your Akka project you should, at a minimum, add the following changes to your application.conf file

    This applied to the client side of a remoting system as well.