我有一个AKKA模型,有一个Supervisor actor可以创建许多子actor。子actor将处理一个事件并将消息发送到另一个服务(例如Kafka主题)。
目前我有一个静态共享类,它在子actor之间共享以发送消息,但在Actor模型中我认为最好使用actor来实现此目的。
我想知道如何创建一个儿童演员可以分享的演员。如果主管演员创建了MessagePublisher actor,孩子们是否可以找到向其发送消息?
谢谢
答案 0 :(得分:0)
根据使用情况,您可以在顶级创建共享Actor
,也可以向主管创建子Actor
。
然后,您只需使用消息或构造函数将ActorRef
传递给主管/子角色,并将其保持为Actor
内部状态。
以下代码应该说明它(它的Scala,但将它转换为Java应该很容易)。
package test
import akka.actor.Actor.Receive
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.stream.ActorMaterializer
object TestClass extends App {
implicit val system = ActorSystem( "ActorSystem" )
implicit val executor = system.dispatcher
implicit val materializer = ActorMaterializer( )
//Option 1 Create as top level actor and pass to supervisor with init message
val sharedActor: ActorRef = system.actorOf( Props[ SharedActor ] )
val supervisor: ActorRef = system.actorOf( Props[ SupervisorActor ] )
supervisor ! InitWithSharedActor( sharedActor )
supervisor ! "NoArgsChild"
supervisor ! "ArgsChild"
class SupervisorActor extends Actor {
private var sharedActor: Option[ ActorRef ] = None
override def preStart( ) = {
//Option 2 Init as child actor of supervisor
println( "Start Supervisor" )
sharedActor = Some( context.actorOf( Props[ SharedActor ] ) )
}
override def receive: Receive = {
case InitWithSharedActor( sa ) =>
sharedActor = Some( sa )
case "NoArgsChild" =>
//Pass to child actor in init msg
sharedActor.foreach( sa => context.actorOf( Props[ ChildActor ] ) ! InitWithSharedActor( sa ) )
case "ArgsChild" =>
//Pass to child with constructor
sharedActor.foreach( sa => context.actorOf( Props( new ChildActorWithArgs( sa ) ) ) )
}
}
class SharedActor extends Actor {
override def preStart( ) = {
println( "Start Shared Actor" )
}
override def receive: Receive = {
case _ =>
}
}
class ChildActor extends Actor {
private var sharedActor: Option[ ActorRef ] = None
override def preStart( ) = {
println( "Start NoArg Child Actor" )
}
override def receive: Receive = {
case InitWithSharedActor( sa ) => sharedActor = Some( sa )
}
}
class ChildActorWithArgs( sharedActor: ActorRef ) extends Actor {
override def preStart( ) = {
println( "Start WithArg Child Actor" )
}
override def receive: Receive = {
case _ =>
}
}
case class InitWithSharedActor( sharedActor: ActorRef )
}