Soumya Simanta
Soumya Simanta

Reputation: 11741

Correct way of creating an ActorSystem inside an Actor

I'm using a third-party library (rediscala) to access a Redis DB inside my own Actor. Following is an example of how I'm currently doing it. Is this correct ? Are there any potential problems with the following code because I'm creating an akkaSystem inside my actor. If SimpleRedisClientActor crashes then I need to restart SimpleRedisClientActor which will create another Actor system. Should I override preStart and postStop ?

import akka.actor.{Props, Actor, ActorLogging}
import redis.RedisClient

import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global

class SimpleRedisClientActor extends Actor with ActorLogging {

  implicit val akkaSystem = akka.actor.ActorSystem()
  val redis = RedisClient()

  def receive: Receive = {

    case PingRedis => {
      val futurePong = redis.ping()
      futurePong.onComplete{
        case Success(s) =>  log.info("Redis replied back with a pong")
        case Failure(f) =>  log.info("Something was wrong ...")
      }
    }
  }
}

object RedisActorDemo extends App {

  implicit val akkaSystem = akka.actor.ActorSystem()
  val simpleActor = akkaSystem.actorOf(Props(classOf[SimpleRedisClientActor]))
  simpleActor ! PingRedis
}

object PingRedis

Upvotes: 0

Views: 727

Answers (1)

Mike Slinn
Mike Slinn

Reputation: 8405

Not a good idea. ActorSystem provides runtime support for actors, so you need an ActorSystem to create an actor, not the other way around. Also, it takes about 500ms to start an ActorSystem, so you would not create lots of them - they are extremely heavyweight. In contrast, Actors are very lightweight. There should only be one ActorSystem per network node.

Upvotes: 3

Related Questions