【问题标题】:Play 2.5 with Akka - could not find implicit value for parameter timeout: akka.util.Timeout使用 Akka 玩 2.5 - 找不到参数超时的隐式值:akka.util.Timeout
【发布时间】:2016-06-21 15:45:49
【问题描述】:

我正在尝试使用 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
  }
}

我的路线如下:

GET     /:name                      controllers.Application.sayHello(name: String)

最后,我的 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

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

could not find implicit value for parameter timeout: akka.util.Timeout

我已经尝试绕过超时但无济于事。有谁知道可能导致此编译错误的原因?

【问题讨论】:

    标签: scala playframework akka


    【解决方案1】:

    您收到此错误是因为 询问模式 需要一个隐式的询问超时(如果这次没有收到任何答复,它将在未来以 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)
        }
      }
    

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

    import scala.concurrent.duration._
    import akka.util.Timeout
    
    implicit val duration: Timeout = 20 seconds
    

    【讨论】:

    • 哇,谢谢!我不敢相信我错过了 - 现在完美无缺。
    • 作为记录,2.5 文档的行如下 implicit val timeout = 5.seconds 无法工作(与上述相同的错误),直到您明确添加 TYPE 如下:implicit val timeout: Timeout = 5.seconds
    • 从 akka 2.5.8 开始,Duration.Inf 不能用于 Timeout,因为它需要有限的持续时间。
    猜你喜欢
    • 1970-01-01
    • 2016-02-08
    • 2013-04-12
    • 1970-01-01
    • 2018-01-06
    • 2016-02-13
    • 2017-02-02
    • 2016-01-17
    • 2011-10-17
    相关资源
    最近更新 更多