@syadav wrote:
Hi, I am new to Akka and developing a spring boot application integrated with Akka.
I have a root actor, which has few child actors. This root actor is the one which receives all the messages then forwards them to child actors based on the type. Now, I want to have only single instance of the root actor in the system, so specified that in the application.conf file. Also, I want to return the same ActorRef of root actor, each time actorOf() is called (since it will receive lot of messages, and I don’t want to create new instance each time , which in turn will create new child actors instances).
So, I created a wrapper over it.RootActor :
@Component("rootActor") @Scope("prototype") public class RootActor extends UntypedActor{ private static final String addOnsActorName = "addOnsActor"; private static final String assetsActorName = "assetsActor"; static volatile ActorRef addOnsActorRef = null; static volatile ActorRef assetsActorRef = null; @Inject private ActorSystem actorSystem; @PostConstruct public void init() { addOnsActorRef = createChild(addOnsActorName); assetsActorRef = createChild(assetsActorName); } public void onReceive(Object arg0) throws Exception { if(!(arg0 instanceof Notification)) { throw new InvalidMessageException("Invalid message!!"); } Notification message = (Notification)arg0; Type type = message.getResourceType(); if(type=="ADDONS") { addOnsActorRef.tell(message, self()); } if(type=="ASSETS") { assetsActorRef.tell(message, self()); } } public ActorRef createChild(String childName) { return getContext().actorOf(SpringExtProvider.get(actorSystem).props(childName).withRouter(new FromConfig()), childName); } }
RootActorWrapper :
@Component public class RootActorWrapper { @Inject ActorSystem actorSystem; protected ActorRef rootActor = null; @PostConstruct public void init() throws ActorException { try { rootActor = actorSystem.actorOf(SpringExtProvider.get(actorSystem) .props("rootActor") .withRouter(new FromConfig()), "rootActor"); } catch (Throwable e) { //handle error } } public void process(Notification notification) { rootActor.tell(notification, null); } }
I want to know if this is alright or is there a better way to do this? Reason I want to keep root actor as singleton because it creates child actors (with 20 instances each). Hence I don’t want new instance of root actor to be created due to each actorOf() call.
So is doing this is okay? Or this is an anti-pattern?
Thanks in advance!
Posts: 5
Participants: 2