使用Akka播放2.5 - 找不到参数超时的隐含值:akka.util.Timeout

Nic*_*ick 6 scala akka playframework

我试图用Play 2.5测试Akka,我遇到了编译错误,我似乎无法绕过.

我在Play文档中关注此页面:https: //playframework.com/documentation/2.5.x/ScalaAkka

这是完整的代码:

package controllers

import javax.inject.{Inject, Singleton}
import akka.actor.ActorSystem
import controllers.HelloActor.SayHello
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.duration._
import akka.pattern.ask

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

  implicit val timeout = 5.seconds

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

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

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
  }
}
Run Code Online (Sandbox Code Playgroud)

我的路线看起来像:

GET     /:name                      controllers.Application.sayHello(name: String)
Run Code Online (Sandbox Code Playgroud)

最后,我的build.sbt:

name := "AkkaTest"

version := "1.0"

lazy val `akkatest` = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.11.7"

libraryDependencies ++= Seq( jdbc , cache , ws   , specs2 % Test )

unmanagedResourceDirectories in Test <+=  baseDirectory ( _ /"target/web/public/test" )  

resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases"

routesGenerator := InjectedRoutesGenerator
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我收到以下编译错误:

could not find implicit value for parameter timeout: akka.util.Timeout
Run Code Online (Sandbox Code Playgroud)

我试过移动超时无济于事.有谁知道可能导致此编译错误的原因是什么?

Max*_*xim 13

您收到此错误是因为询问模式需要隐式超时询问(TimeoutException如果此时未收到答复,它将完成将来).所以你需要的是在这样的sayHello方法中创建一个隐式的本地值:

import akka.util.Timeout
import scala.concurrent.duration.Duration

// ...

  def sayHello(name: String) = Action.async {
    implicit val timeout: Timeout = Duration.Infinite
    (helloActor ? SayHello(name)).mapTo[String].map { message =>
      Ok(message)
    }
  }
Run Code Online (Sandbox Code Playgroud)

您可以使用以下语法指定有限的超时,而不是指定无限超时:

import scala.concurrent.duration._
import akka.util.Timeout

implicit val duration: Timeout = 20 seconds
Run Code Online (Sandbox Code Playgroud)