I wrote this code to create a remote actor
object Main extends App {
val system = ActorSystem("keyvalue")
system.actorOf(Props[KeyValueActor], name = "keyvalue-db")
}
class KeyValueActor extends Actor {
val map = new util.HashMap[String, Object]
val log = Logging(context.system, this)
override def receive = {
case SetRequest(key, value) => {
log.info(s"received set request key ${key} value ${value}")
map.put(key, value)
sender() ! Status.Success
}
case GetRequest(key) => log.info(s"recieved get request ${key}")
sender() ! KeyValue(map.get(key))
case _=> log.info("unknown message")
}
}
I started my server using activator run and this printed the message
[info] Running com.abhi.akka.Main
[INFO] [01/10/2016 20:21:52.461] [run-main-0] [Remoting] Starting remoting
[INFO] [01/10/2016 20:21:52.617] [run-main-0] [Remoting] Remoting started;
listening on addresses :[akka.tcp://keyvalue#127.0.0.1:2552]
[INFO] [01/10/2016 20:21:52.619] [run-main-0] [Remoting]
Remoting now listens on addresses: [akka.tcp://keyvalue#127.0.0.1:2552]
but now when i try to call my remote actor using this client code
object KeyValueClient {
def main(args: Array[String]) : Unit = {
implicit val system = ActorSystem("LocalFileSystem")
implicit val timeout = Timeout(2 seconds)
val keyValueActorRef = system.actorSelection("akka.tcp://keyvalue#127.0.0.1:2552/user/keyvalue-db")
keyValueActorRef ! SetRequest("foo", "bar")
(keyValueActorRef ? GetRequest("foo")).onSuccess({
case x : KeyValue => println(s"got value ${x.value}")
})
}
}
it throws an error message
[INFO] [01/10/2016 20:25:33.345] [LocalFileSystem-akka.actor.default-dispatcher-2] [akka://LocalFileSystem/deadLetters] Message [com.abhi.akka.messages.SetRequest] from Actor[akka://LocalFileSystem/deadLetters] to Actor[akka://LocalFileSystem/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'.
[INFO] [01/10/2016 20:25:33.346] [LocalFileSystem-akka.actor.default-dispatcher-2] [akka://LocalFileSystem/deadLetters] Message [com.abhi.akka.messages.GetRequest] from Actor[akka://LocalFileSystem/temp/$a] to Actor[akka://LocalFileSystem/deadLetters] was not delivered. [2] 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'.
My Full code is available at
https://github.com/abhitechdojo/keyvaluedb.git
https://github.com/abhitechdojo/keyvalueclient.git
EDIT: I solved the problem based on the suggestion given by Mustafa Simov. The client side needed this configuration file
akka {
actor {
provider = "akka.remote.RemoteActorRefProvider"
deployment {
/keyvalue-db {
remote = "akka.tcp://keyvalue#127.0.0.1:2552"
}
}
}
}
Then you create the actor using
val actor = system.actorOf(Props[KeyValueActor], "keyvalue-db")
I have looked at your client code and I think it is just a configuration problem. In order to use akka-remoting, you must configure your client too. So you must create an application.conf for client ActorSystem as you created for server.
Akka remoting is peer-to-peer and not really a good fit for client-server
Because of this both sides in remoting must be able to connect to the other side, as either of them can initiate communication. Both of your applications therefore needs to configure a remoting actor-ref provider and host+port pair that the other node can connect through. You can read details about how to do this in the akka docs here.
Related
I'm trying to test a simple actor which is connecting to another remote on tcp. Here is my actor
/**
* Created by chris on 6/6/16.
*/
class Client(listener : ActorRef, actorSystem: ActorSystem) extends Actor with BitcoinSLogger {
/**
* The manager is an actor that handles the underlying low level I/O resources (selectors, channels)
* and instantiates workers for specific tasks, such as listening to incoming connections.
*/
def manager = IO(Tcp)(actorSystem)
def receive = {
case Tcp.Connect(remote,_,_,_,_) => manager ! Tcp.Connect(remote)
case Tcp.CommandFailed(_: Tcp.Connect) =>
logger.debug("Connection failed")
listener ! "connect failed"
context stop self
case c # Tcp.Connected(remote, local) =>
logger.debug("Tcp connection to: " + remote)
logger.debug("Local: " + local)
listener ! c
val connection = sender()
connection ! Tcp.Register(self)
context become {
case data: ByteString =>
connection ! Tcp.Write(data)
case Tcp.CommandFailed(w: Tcp.Write) =>
// O/S buffer was full
listener ! "write failed"
case Tcp.Received(data) =>
listener ! data
case "close" =>
connection ! Tcp.Close
case _: Tcp.ConnectionClosed =>
listener ! "connection closed"
context stop self
}
}
def sendMessage(msg : NetworkRequest, peer : NetworkIpAddress) : Future[NetworkResponse] = ???
}
object Client {
//private case class ClientImpl(remote: InetSocketAddress, listener: ActorRef, actorSystem : ActorSystem) extends Client
def apply(listener : ActorRef, actorSystem : ActorSystem) : Props = {
Props(classOf[Client], listener, actorSystem)
}
}
here is my test case
class ClientTest extends TestKit(ActorSystem("ClientTest")) with FlatSpecLike with MustMatchers with BeforeAndAfterAll {
"Client" must "connect to a node on the bitcoin network" in {
val probe = TestProbe()
val hostName = "testnet-seed.bitcoin.schildbach.de"
val socket = new InetSocketAddress(hostName, TestNet3.port)
val peerMessageHandler = PeerMessageHandler(system)
val client = system.actorOf(Client(peerMessageHandler, system))
probe.send(client, Tcp.Connect(socket))
probe.expectMsgType[Tcp.Connected](10.seconds)
}
override def afterAll: Unit = {
TestKit.shutdownActorSystem(system)
}
}
finally, I can tell the connection is successful because my log messages are being hit:
2016-06-08 09:58:21,548 - [DEBUG] - from class
org.bitcoins.spvnode.networking.Client in
ClientTest-akka.actor.default-dispatcher-4 Tcp connection to:
testnet-seed.bitcoin.schildbach.de:18333
2016-06-08 09:58:21,550 - [DEBUG] - from class
org.bitcoins.spvnode.networking.Client in
ClientTest-akka.actor.default-dispatcher-4 Local:
/192.168.1.107:43782
however my test case is failing with this error
[info] ClientTest:
[info] Client
[info] - must connect to a node on the bitcoin network *** FAILED ***
[info] java.lang.AssertionError: assertion failed: timeout (10 seconds) during expectMsgClass waiting for class akka.io.Tcp$Connected
[info] at scala.Predef$.assert(Predef.scala:170)
[info] at akka.testkit.TestKitBase$class.expectMsgClass_internal(TestKit.scala:435)
[info] at akka.testkit.TestKitBase$class.expectMsgType(TestKit.scala:417)
[info] at akka.testkit.TestKit.expectMsgType(TestKit.scala:737)
[info] at org.bitcoins.spvnode.networking.ClientTest$$anonfun$1.apply$mcV$sp(ClientTest.scala:25)
[info] at org.bitcoins.spvnode.networking.ClientTest$$anonfun$1.apply(ClientTest.scala:17)
[info] at org.bitcoins.spvnode.networking.ClientTest$$anonfun$1.apply(ClientTest.scala:17)
[info] at org.scalatest.Transformer$$anonfun$apply$1.apply$mcV$sp(Transformer.scala:22)
[info] at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
[info] at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
[info] ...
Seems like I am missing something simple, but I can't figure out exactly what it is.
To answer my own question, I just made probe the listener isntead of trying to listen on the Client actor itself.
"Client" must "connect to a node on the bitcoin network" in {
val probe = TestProbe()
val hostName = "testnet-seed.bitcoin.schildbach.de"
val socket = new InetSocketAddress(hostName, TestNet3.port)
val peerMessageHandler = PeerMessageHandler(system)
val client = TestActorRef(Client(probe.ref,system))
//probe.send(client, Tcp.Connect(socket))
client ! Tcp.Connect(socket)
probe.expectMsgType[Tcp.Connected](10.seconds)
}
i am new for Akka, i am using Akka 2.3.3 version for creating actors. I am going to create remote actor and trying to access with client. Whenever i am going to run test-case, the following exception will throw:
[INFO] [04/27/2016 07:51:23.727] [Localsystem-akka.actor.default-dispatcher-3] [akka://Localsystem/deadLetters] Message [com.harmeetsingh13.chapter2.messages.SetRequest] from Actor[akka://Localsystem/temp/$a] to Actor[akka://Localsystem/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'.
[INFO] [04/27/2016 07:51:23.745] [Localsystem-akka.actor.default-dispatcher-3] [akka://Localsystem/deadLetters] Message [com.harmeetsingh13.chapter2.messages.GetRequest] from Actor[akka://Localsystem/temp/$b] to Actor[akka://Localsystem/deadLetters] was not delivered. [2] 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'.
Futures timed out after [10 seconds]
java.util.concurrent.TimeoutException: Futures timed out after [10 seconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:219)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:223)
at scala.concurrent.Await$$anonfun$result$1.apply(package.scala:190)
at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53)
at scala.concurrent.Await$.result(package.scala:190)
at com.harmeetsingh13.chapter2.SClientIntegrationSpec$$anonfun$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(SClientIntegrationSpec.scala:18)
at com.harmeetsingh13.chapter2.SClientIntegrationSpec$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(SClientIntegrationSpec.scala:15)
at com.harmeetsingh13.chapter2.SClientIntegrationSpec$$anonfun$1$$anonfun$apply$mcV$sp$1.apply(SClientIntegrationSpec.scala:15)
at org.scalatest.Transformer$$anonfun$apply$1.apply$mcV$sp(Transformer.scala:22)
at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
at org.scalatest.Transformer.apply(Transformer.scala:22)
at org.scalatest.Transformer.apply(Transformer.scala:20)
at org.scalatest.FunSpecLike$$anon$1.apply(FunSpecLike.scala:422)
at org.scalatest.Suite$class.withFixture(Suite.scala:1122)
at com.harmeetsingh13.chapter2.SClientIntegrationSpec.withFixture(SClientIntegrationSpec.scala:11)
at org.scalatest.FunSpecLike$class.invokeWithFixture$1(FunSpecLike.scala:419)
at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:431)
at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:431)
at org.scalatest.SuperEngine.runTestImpl(Engine.scala:306)
at org.scalatest.FunSpecLike$class.runTest(FunSpecLike.scala:431)
at com.harmeetsingh13.chapter2.SClientIntegrationSpec.runTest(SClientIntegrationSpec.scala:11)
at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:464)
at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:464)
at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:413)
at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:401)
............
My Server code as below:
Main.scala
object Main extends App{
private val configFile = getClass.getClassLoader.getResource("application.conf").getFile;
private val config = ConfigFactory.parseFile(new File(configFile ))
val system = ActorSystem("SimpleClientServer", config)
system.actorOf(Props[AkkadmeyDB], name = "akkademy-db")
}
application.conf:
akka{
actor{
provider = "akka.remote.RemoteActorRefProvider"
}
remote{
enabled-transports = ["akka.remote.netty.tcp"]
netty.tcp {
hostname = "127.0.0.1"
port = 2552
}
log-sent-messages = on
log-received-messages = on
}
}
AkkadmeyDB.scala Actor class:
class AkkadmeyDB extends Actor{
val map = new HashMap[String, Object]
val log = Logging(context.system, this)
override def receive: Receive = {
case SetRequest(key, value) =>
log.info("received SetRequest - key: {} value: {}", key, value)
map.put(key, value)
sender() ! Status.Success
case GetRequest(key) =>
log.info("received GetRequest - key: {}", key)
val response = map.get(key)
response match{
case Some(x) => sender() ! x
case None => Status.Failure(new KeyNotFoundException(key))
}
case o => Status.Failure(new ClassNotFoundException())
}
}
Client Code as below:
SClient.scala
class SClient(remoteIp: String) {
private implicit val timeout = Timeout(10 seconds)
private implicit val system = ActorSystem("Localsystem")
private val remoteAddress = s"akka.tcp://SimpleClientServer#$remoteIp/user/akkademy-db";
private val remoteDb = system.actorSelection(remoteAddress)
def set(key: String, value: Object) = {
remoteDb ? SetRequest(key, value)
}
def get(key: String) = {
remoteDb ? GetRequest(key)
}
}
SClientIntegrationSpec.scala Test case:
class SClientIntegrationSpec extends FunSpecLike with Matchers {
val client = new SClient("127.0.0.1:2552")
describe("akkadment-db-client"){
it("should set a value"){
client.set("jame", new Integer(1313))
val futureResult = client.get("james")
val result = Await.result(futureResult, 10 seconds)
result should equal (1313)
}
}
}
When i see the logs of my remote application, this seems like, the request hit doesn't go to the server. what is the problem in my sample code running?
For solving above problem, we need to follow two steps that are metnion below:
When i am creating a server code, i am excluding application.conf from my server application, that's why, client application not able to connect with server. The code are using in built.sbt is as below:
mappings in (Compile, packageBin) ~= { _.filterNot { case (_, name) =>
Seq("application.conf").contains(name)
}}
After commenting above code, the client see the server successfully.
In Learning Scala chapter 2 jasongoodwin explain the code of client and server actor system. But there are some Errata in book and missing application.conf configuration for client. Because when we run both code in same PC, we are facing already port bind exception because by default actors are using 2552 port for accessing and we already define this port for our server application. So, application.conf also need for client as below:
akka {
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
remote {
enabled-transports = ["akka.remote.netty.tcp"]
netty.tcp {
hostname = "127.0.0.1"
port = 0
}
log-sent-messages = on
log-received-messages = on
}
}
Here Port 0 means any free port.
After that, above code are running successfully.
There is an application.conf file in the client project as well which is not mentioned in the book.
Make sure you create that file under the resources folder with the following content:
akka {
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
}
See the official github repo
I just started learning Scala and Akka and now I am trying to develop an application that uses ReactiveMongo framework to connect to a MongoDb server.
The problem is that when I call system.shutdown() in the end of my App object, the process does not terminate and just hangs forever.
I am now testing the case when there is no connection available, so my MongoDB server is not running. I have the following actor class for querying the database:
class MongoDb(val db: String, val nodes: Seq[String], val authentications: Seq[Authenticate] = Seq.empty, val nbChannelsPerNode: Int = 10) extends Actor with ActorLogging {
def this(config: Config) = this(config.getString("db"), config.getStringList("nodes").asScala.toSeq,
config.getList("authenticate").asScala.toSeq.map(c => {
val l = c.unwrapped().asInstanceOf[java.util.HashMap[String, String]]; Authenticate(l.get("db"), l.get("user"), l.get("password"))
}),
config.getInt("nbChannelsPerNode"))
implicit val ec = context.system.dispatcher
val driver = new MongoDriver(context.system)
val connection = driver.connection(nodes, authentications, nbChannelsPerNode)
connection.monitor.ask(WaitForPrimary)(Timeout(30.seconds)).onFailure {
case reason =>
log.error("Waiting for MongoDB primary connection timed out: {}", reason)
log.error("MongoDb actor kills itself as there is no connection available")
self ! PoisonPill
}
val dbConnection = connection(db)
val tasksCollection = dbConnection("tasks")
val taskTargetsCollection = dbConnection("taskTargets")
import Protocol._
override def receive: Receive = {
case GetPendingTask =>
sender ! NoPendingTask
}
}
My app class looks like this:
object HelloAkkaScala extends App with LazyLogging {
import scala.concurrent.duration._
// Create the 'helloakka' actor system
val system = ActorSystem("helloakka")
implicit val ec = system.dispatcher
//val config = ConfigFactory.load(ConfigFactory.load.getString("my.helloakka.app.environment"))
val config = ConfigFactory.load
logger.info("Creating MongoDb actor")
val db = system.actorOf(Props(new MongoDb(config.getConfig("my.helloakka.db.MongoDb"))))
system.scheduler.scheduleOnce(Duration.create(60, TimeUnit.SECONDS), new Runnable() { def run() = {
logger.info("Shutting down the system")
system.shutdown()
logger.info("System has been shut down!")
}})
}
And the log output in my terminal looks like this:
[DEBUG] [08/07/2014 00:32:06.358] [run-main-0] [EventStream(akka://helloakka)] logger log1-Logging$DefaultLogger started
[DEBUG] [08/07/2014 00:32:06.358] [run-main-0] [EventStream(akka://helloakka)] Default Loggers started
00:32:06.443 INFO [run-main-0] [HelloAkkaScala$] - Creating MongoDb actor
00:32:06.518 DEBUG [helloakka-akka.actor.default-dispatcher-3] [reactivemongo.core.actors.MonitorActor] - Actor[akka://helloakka/temp/$a] is waiting for a primary... not available, warning as soon a primary is available.
00:32:06.595 DEBUG [helloakka-akka.actor.default-dispatcher-2] [reactivemongo.core.actors.MongoDBSystem] - Channel #-774976050 unavailable (ChannelClosed(-774976050)).
00:32:06.599 DEBUG [helloakka-akka.actor.default-dispatcher-2] [reactivemongo.core.actors.MongoDBSystem] - The entire node set is still unreachable, is there a network problem?
00:32:06.599 DEBUG [helloakka-akka.actor.default-dispatcher-2] [reactivemongo.core.actors.MongoDBSystem] - -774976050 is disconnected
00:32:08.573 DEBUG [helloakka-akka.actor.default-dispatcher-3] [reactivemongo.core.actors.MongoDBSystem] - ConnectAll Job running... Status: Node[localhost: Unknown (0/10 available connections), latency=0], auth=Set()
00:32:08.574 DEBUG [helloakka-akka.actor.default-dispatcher-3] [reactivemongo.core.actors.MongoDBSystem] - Channel #-73322193 unavailable (ChannelClosed(-73322193)).
00:32:08.575 DEBUG [helloakka-akka.actor.default-dispatcher-3] [reactivemongo.core.actors.MongoDBSystem] - The entire node set is still unreachable, is there a network problem?
00:32:08.575 DEBUG [helloakka-akka.actor.default-dispatcher-3] [reactivemongo.core.actors.MongoDBSystem] - -73322193 is disconnected
... (the last 3 messages repeated many times as per documentation the MongoDriver tries to re-connect with 2 seconds interval)
[ERROR] [08/07/2014 00:32:36.474] [helloakka-akka.actor.default-dispatcher-3] [akka://helloakka/user/$a] Waiting for MongoDB primary connection timed out: akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://helloakka/user/$c#1684233695]] after [30000 ms]
[ERROR] [08/07/2014 00:32:36.475] [helloakka-akka.actor.default-dispatcher-3] [akka://helloakka/user/$a] MongoDb actor kills itself as there is no connection available
... (the same 3 messages repeated again)
00:32:46.461 INFO [helloakka-akka.actor.default-dispatcher-4] [HelloAkkaScala$] - Shutting down the system
00:32:46.461 INFO [helloakka-akka.actor.default-dispatcher-4] [HelloAkkaScala$] - Awaiting system termination...
00:32:46.465 WARN [helloakka-akka.actor.default-dispatcher-2] [reactivemongo.core.actors.MongoDBSystem] - MongoDBSystem Actor[akka://helloakka/user/$b#537715233] stopped.
00:32:46.465 DEBUG [helloakka-akka.actor.default-dispatcher-5] [reactivemongo.core.actors.MonitorActor] - Monitor Actor[akka://helloakka/user/$c#1684233695] stopped.
[DEBUG] [08/07/2014 00:32:46.468] [helloakka-akka.actor.default-dispatcher-2] [EventStream] shutting down: StandardOutLogger started
00:32:46.483 INFO [helloakka-akka.actor.default-dispatcher-4] [HelloAkkaScala$] - System has been terminated!
And after that the process hands forever and does never terminate. What am I doing wrong?
You aren't doing anything incorrect. This is a known issue.
https://github.com/ReactiveMongo/ReactiveMongo/issues/148
I am trying to run remote actors using AKKA, on my localhost, but each time I get this error. It says dead letters encountered. I searched on internet and found out that this error comes when actors receive a message after its thread is stopped. So I am looking for a way to keep the actors alive on remote machines. I am using akka actors and not the scala actors.
[INFO] [09/16/2013 18:44:51.426] [run-main] [Remoting] Starting remoting
[INFO] [09/16/2013 18:44:51.688] [run-main] [Remoting] Remoting started; listening on addresses :[akka.tcp://actorSystem1#localhost:2209]
[INFO] [09/16/2013 18:44:51.759] [actorSystem2-akka.actor.default-dispatcher-5] [akka://actorSystem2/deadLetters] Message [java.lang.String] from
Actor[akka://actorSystem2/deadLetters] to Actor[akka://actorSystem2/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'.
Following is the code.
import akka.actor.{Actor, Props, ActorSystem}
import com.typesafe.config.ConfigFactory
import akka.remote._
object MyApp extends App {
val actorSystem1 = ActorSystem("actorSystem1", ConfigFactory.parseString("""
akka {
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
remote {
transport = ["akka.remote.netty.tcp"]
netty.tcp {
hostname = "localhost"
port = 2209
}
}
}
"""))
val actorSystem2 = ActorSystem("actorSystem2")
actorSystem1.actorOf(Props(new Actor {
def receive = {
case x: String =>
Thread.sleep(1000)
println("RECEIVED MESSAGE: " + x)
} }), "simplisticActor")
val remoteActor = actorSystem2.actorFor("akka://actorSystem1#localhost:2209/user/simplisticActor")
remoteActor ! "TEST 1"
remoteActor ! "TEST 2"
Thread.sleep(1000)
actorSystem1.shutdown()
actorSystem2.shutdown()
}
Thanks in advance.
I think I see a few issues with your code that might be leading to deadletters. First, if your intention is to lookup an actor on a remote system from actorSystem2 into actorSystem1, then you will still need to set up remoting properties for actorSystem1, most specifically, you need to make sure it's using the RemoteActorRefProvider. If you don't do this, system 2 will not be able to lookup a remote actor in system 1. Once you make this change, I would also change your remote actor lookup from:
val remoteActor = actorSystem2.actorFor("akka://actorSystem1#localhost:2209/user/simplisticActor")
to:
val remoteActor = actorSystem2.actorSelection("akka.tcp://actorSystem1#localhost:2209/user/simplisticActor")
The actorFor method has been deprecated and also I think you left off the .tcp part of the akka protocol for looking up the remote actor.
Make these changes and then see if things work for you.
EDIT Notice, I needed to make the reverse changes of this https://github.com/akka/akka/commit/ce014ece3568938b2036c4ccfd21b92faba69607#L13L6 to make the accepted answer work with AKKA 2.1 which is the stable distribution found on akkas homepage!
I have read all the tutorials I could find on AKKA, but nothing I found works "out of box".
Using eclipse, I want to create 2 programs.
Program1:
starts actor "joe" and somehow makes it available on 127.0.0.1:some_port
Program2:
gets a reference to actor "joe" at 127.0.0.1:some_port. Sends a hello message to "joe".
Program 1 should print something when the message is received. I want to run this example in eclipse using AKKA 2.1. Can someone list 2 programs, (program1 and program2) together with a working application.conf file that does this and nothing else?
edit>
let me show you what I got so far:
actor
case class Greeting(who: String) extends Serializable
class GreetingActor extends Actor with ActorLogging {
def receive = {
case Greeting(who) ⇒ println("Hello " + who);log.info("Hello " + who)
}
}
Program1:
package test
import akka.actor.ActorSystem
object Machine1 {
def main(args: Array[String]): Unit = {
val system = ActorSystem("MySystem")
}
}
Program2
package test
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.actorRef2Scala
object Machine2 {
def main(args: Array[String]): Unit = {
val system = ActorSystem("MySystem")
val greeter = system.actorOf(Props[GreetingActor], name = "greeter")
greeter ! Greeting("Felix")
}
}
application.conf
akka {
actor {
deployment {
/greeter {
remote = "akka://MySystem#127.0.0.1:2553"
}
}
}
}
However, this program works when I start only Program2 and it outputs:
Hello Felix
[INFO] [02/18/2013 12:27:29.999] [MySystem-akka.actor.default-dispatcher-2] [akka://MySystem/user/greeter] Hello Felix
It seems that it is not picking up my application.conf. I tried placing it both in the ./src/ and ./ folder of my eclipse project. No difference. Also, I know this is really demote deployment, but I need just a hello world program to work using AKKA. I spent so much time on this without getting a simple working application.
Update for Akka 2.2.3
A minimal remote application can be created as follows:
Create 2 Projects in Eclipse: Client and Server
Server:
The code for the server is
package server
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorSystem
import akka.actor.Props
class Joe extends Actor {
def receive = {
case msg: String => println("joe received " + msg + " from " + sender)
case _ => println("Received unknown msg ")
}
}
object Server extends App {
val system = ActorSystem("GreetingSystem")
val joe = system.actorOf(Props[Joe], name = "joe")
println(joe.path)
joe ! "local msg!"
println("Server ready")
}
The applincation.conf for the server is
akka {
loglevel = "DEBUG"
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
remote {
enabled-transports = ["akka.remote.netty.tcp"]
netty.tcp {
hostname = "127.0.0.1"
port = 2552
}
log-sent-messages = on
log-received-messages = on
}
}
Client:
The Client-code is
package client
import akka.actor._
import akka.actor.ActorDSL._
object Greet_Sender extends App {
println("STARTING")
implicit val system = ActorSystem("GreetingSystem-1")
val joe = system.actorSelection("akka.tcp://GreetingSystem#127.0.0.1:2552/user/joe")
println("That 's Joe:" + joe)
val a = actor(new Act {
whenStarting { joe ! "Hello Joe from remote" }
})
joe ! "Hello"
println("Client has sent Hello to joe")
}
The client application.conf is:
akka {
#log-config-on-start = on
stdout-loglevel = "DEBUG"
loglevel = "DEBUG"
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
remote {
enabled-transports = ["akka.remote.netty.tcp"]
log-sent-messages = on
log-received-messages = on
netty.tcp {
hostname = "127.0.0.1"
port = 0
}
}
}
Configurations have to be placed in two files called application.conf, both within the bin directory of the two projects.
As korefn mentioned, the remote documentation explains it's workings in detail. It also links to an example application. That example should give you everything you need to get started.
Edit
To get the sample application running perform the following steps:
Clone from GitHub
eecolor#BLACK:~/GihHub$ git clone https://github.com/akka/akka.git
Go into the akka directory and run sbt
eecolor#BLACK:~/GihHub/akka$ sbt
Switch to the akka-sample-project
akka > project akka-sample-remote
Call run on the project and select the CalcApp
Multiple main classes detected, select one to run:
[1] sample.remote.calculator.java.JCreationApp
[2] sample.remote.calculator.LookupApp
[3] sample.remote.calculator.CalcApp
[4] sample.remote.calculator.java.JLookupApp
[5] sample.remote.calculator.CreationApp
[6] sample.remote.calculator.java.JCalcApp
Enter number: 3
[info] Running sample.remote.calculator.CalcApp
[INFO] [02/19/2013 19:22:09.055] [run-main] [Remoting] Starting remoting
[INFO] [02/19/2013 19:22:09.230] [run-main] [Remoting] Remoting started; listening on addresses :[akka.tcp://CalculatorApplication#127.0.0.1:2552]
Started Calculator Application - waiting for messages
Switch to another console and repeat the first few steps
eecolor#BLACK:~/GihHub/akka$ sbt
akka > project akka-sample-remote
Call run and select the LookupApp
akka-sample-remote > run
Multiple main classes detected, select one to run:
[1] sample.remote.calculator.java.JCreationApp
[2] sample.remote.calculator.LookupApp
[3] sample.remote.calculator.CalcApp
[4] sample.remote.calculator.java.JLookupApp
[5] sample.remote.calculator.CreationApp
[6] sample.remote.calculator.java.JCalcApp
Enter number: 2
[info] Running sample.remote.calculator.LookupApp
[INFO] [02/19/2013 19:23:39.358] [run-main] [Remoting] Starting remoting
[INFO] [02/19/2013 19:23:39.564] [run-main] [Remoting] Remoting started; listening on addresses :[akka.tcp://LookupApplication#127.0.0.1:2553]
Started Lookup Application
Sub result: 14 - 16 = -2
Sub result: 13 - 22 = -9
Add result: 56 + 93 = 149
Add result: 18 + 19 = 37
Switch back to the other console and you should see something like this:
Calculating 14 - 16
Calculating 13 - 22
Calculating 56 + 93
Calculating 18 + 19
Well, in your example, the Client code never references the config file and it won't work.
akka by default will use the application.conf file - so it does not need to be explicitly selected.
if one does want to then the code would be (taking the code above as an exmaple):
val configFile = getClass.getClassLoader.getResource("akka_local_application.conf").getFile
val config = ConfigFactory.parseFile(new File(configFile))
val system = ActorSystem("GreetingSystem",config)
val joe = system.actorOf(Props[Joe], name = "joe")