Reputation: 373
I have two classes with different ActorSystem with their corresponding actors. How can actor from class1 send message to actor in class2?
Upvotes: 1
Views: 2264
Reputation: 24040
See the docs on Actor Paths. The actor path includes the actor system.
So for example if your actor systems are named system1
and system2
, and both of your actors are top level actors named actor1
and actor2
, you can get ActorRefs
for them like:
// inside actor1
val actor2 = system.actorFor("akka://system2/user/actor2")
actor2 ! "Foo"
and
// inside actor2
val actor1 = system.actorFor("akka://system1/user/actor1")
actor1 ! "bar"
Upvotes: 0
Reputation: 24413
Why do you have 2 ActorSystem
s? Unless you have a really good reason, you should create all your actors in the same ActorSystem
. Creating an ActorSystem
is very expensive and communication as well as error handling are harder. Here's a simple example of communication between actors:
class Foo extends Actor {
val barActor = context.actorFor("/user/bar")
def receive = {
case 'Send => barActor ! "message from foo!"
}
}
class Bar extends Actor {
def receive = {
case x => println("Got " + x)
}
}
object Main {
def main(args: Array[String]) {
val system = ActorSystem("MySystem")
val foo = system.actorOf(Props[Foo], "foo")
val bar = system.actorOf(Props[Bar], "bar")
foo ! 'Send
}
}
With system.actorFor
or context.actorFor
, you can retrieve an ActorRef
for a given path. The path for user created actors always starts with /user
and includes all parent actors. So if you have a hierarchy of 3 actors the path could be /user/actorA/actorB/actorC
.
Upvotes: 5
Reputation: 37660
I am not really sure what are you asking about.
If the actor class is MyClass
and the message object is Message
, you just do
val myInstance = new MyClass()
myInstance ! Message
And that's it. You can call that from within any other actor.
Upvotes: -1