我有以下代码需要运行100次:
val system = ActorSystem("mySystem")
val myActorObject = system.actorOf(Props[MyActorClass], name = "myactor")
implicit val timeout = Timeout(60 seconds)
val future = myActorObject ? Request1
val result = Await.result(future, timeout.duration)
问题是:假设前两个语句只能被调用一次,我应该缓存这些变量还是Akka呢?
答案 0 :(得分:1)
不要让actor系统创建和actor创建成为重复代码的一部分。一旦创建了演员。使用ActorRef可以尽可能多地完成。
val system = ActorSystem("mySystem")
val myActorObject = system.actorOf(Props[MyActorClass], name = "myactor")
像这样的东西
val futureList = for(_ <- 1 to 1000) yield {
implicit val timeout = Timeout(60 seconds)
val future = myActorObject ? Request1
}
val finalF = Future.sequence(futureList)
val result = Await.result(future, timeout.duration)
答案 1 :(得分:1)
在游戏中! (+ 2.5.x)您可以通过注入获得系统。 e.g。
@Singleton
class MyController @Inject() (system: ActorSystem) extends Controller {
val myActor = system.actorOf(MyActorClass.props, "myactor")
//...
}
然后你可以有一个终点来根据需要多次调用actor,例如
def sayHello(name: String) = Action.async {
(myActor ? name).map { message => Ok(message) }
}
你演员中的代码可能是这样的
class MyActorClass extends Actor {
def receive = {
case name: String => sender() ! s"hello $name"
}
}
object MyActorClass {
def props: Props = Props(classOf[MyActorClass ])
}