문제

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
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top