如何使用Akka演员的@Singleton?

时间:2016-10-03 12:47:36

标签: scala dependency-injection akka

我是Dependency Injection的新手,现在当我将我的应用程序迁移到Play 2.5.x时,我需要学习。

我的单身服务看起来像这样:

import javax.inject._
@Singleton
class WorkerService {
   def doWork(work:String) {
      ...
   }
}

我有一个演员看起来像这样:

import scala.concurrent.duration.DurationInt
import scala.language.postfixOps
import akka.actor._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scalaj.http._

import WorkerService

object PollActor {
  def props(host: String) = Props(new PollActionActor(host))
}

// Actor that polls a host for information
class PollActor(host: String) extends Actor with ActorLogging {
    // timer for poll
    var timer: Cancellable = context.system.scheduler.schedule(0 second, 10 second, self, TimeStep())

    // handle messages
    override def receive = {
        case TimeStep() =>
            getWork match {
                case Some(work:String) =>
                    // How to do this?: ChecklistService.doWork(work)
                case None =>
            }
    }

    def getWork = {
        try {
            Some(Http(host)
                    .option(HttpOptions.readTimeout(10000))
                    .option(HttpOptions.connTimeout(10000))
                    .asString.body)
        } catch {
          case _:Throwable =>
            None
        }
    }

    case class TimeStep()
}

一个像这样的控制器:

@Singleton
class Application @Inject() (implicit system: ActorSystem) extends Controller {
    val pollActor = system.actorOf(PollActor.props("127.0.0.1"))

    def index = Action {
        pollActor ! TimeStep
    }
}

如何在演员的时间步骤中调用WorkerService.doWork

1 个答案:

答案 0 :(得分:1)

您可能不应该在Application类中创建actor。

尝试使用模块来创建这样的演员

class ApplicationConfigModule extends AbstractModule with AkkaGuiceSupport {

  override def configure(): Unit = {
    bindActor[PollActor]("poll-actor")
  }
}
你的资源/ application.conf中的

把这个

play.modules.enabled += "com.nowtv.platform.search.module.ApplicationConfigModule"

然后将服务注入您的演员

class PollActor @Inject()(WorkerService: workerService) extends Actor 

将Actor注入Controller,以便在那里使用

@Singleton
class Application @Inject() (@Named("poll-actor") pollActor: ActorRef) extends Controller {