在Scala的Play Framework 2.4中实现Akka

时间:2015-10-20 10:06:13

标签: scala akka playframework-2.4

我试图复制Integrating with Akka, Play 2.4 for Scala doc中提出的基本示例。但我把最后的作品放在一起很困难......

我已使用以下代码在app/actors/HelloActor.scala定义了演员(请参阅Writing actors段):

package actors

import akka.actor._

object HelloActor {
    def props = Props[HelloActor]

    case class SayHello(name: String)
}

class HelloActor extends Actor {
    import HelloActor._

    def receive = {
        case SayHello(name: String) =>
            sender() ! "Hello, " + name
    }
}

然后(见Creating and using actors)我想我应该在app/controllers/Hello.scala创建一个控制器,例如:

package controllers

import play.api.mvc._
import akka.actor._
import javax.inject._

import actors.HelloActor

@Singleton
class Hello @Inject() (system: ActorSystem) extends Controller {

    val helloActor = system.actorOf(HelloActor.props, "hello-actor")

    ...

}

问题:我在何处以及如何利用以下段落Asking things of actors中的代码来获得有效的解决方案?我试图将它添加到上面的Hello.scala控制器但没有成功。

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.duration._
import akka.pattern.ask
implicit val timeout = 5.seconds

def sayHello(name: String) = Action.async {
    (helloActor ? SayHello(name)).mapTo[String].map { message =>
        Ok(message)
    }
}

1 个答案:

答案 0 :(得分:0)

找到解决方案,我在定义隐式超时方面遇到了一些问题,这是工作控制器:

package controllers

import play.api.mvc._
import akka.actor._
import javax.inject._

import actors.HelloActor
import actors.HelloActor.SayHello

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.duration._
import akka.pattern.ask
import akka.util.Timeout

@Singleton
class Hello @Inject() (system: ActorSystem) extends Controller {

  val helloActor = system.actorOf(HelloActor.props, "hello-actor")

  implicit val timeout: Timeout = 5.seconds

  def sayHello(name: String) = Action.async { 

    (helloActor ? SayHello(name)).mapTo[String].map { message ⇒
      Ok(message)
    }
  }
}

另外,我在app/conf/routes中添加了以下路线:

# Actor test
GET     /hello/:name                controllers.Hello.sayHello(name)