Scala编译器无法在路由声明中找到解组的含义

时间:2017-06-02 09:33:33

标签: scala implicit akka-http

我正在尝试使用本教程构建REST服务器:

https://spindance.com/reactive-rest-services-akka-http/

然而,已经达到了#34;响应JSON"部分,我注意到我的代码没有编译,我也无法发出POST请求。这是我得到的错误:

Error:(59, 18) could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[Health]
        entity(as[Health]) { statusReport =>
                 ^

看过其他教程之后,我发现你需要为我试图解组的类包含一个包含隐式变量的对象。我做到了,我甚至导入了httpx库,但我仍然遇到这个错误。我的代码如下。

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import akka.pattern.ask
import akka.util.Timeout

import spray.json._
import DefaultJsonProtocol._
import spray.httpx.SprayJsonSupport.sprayJsonUnmarshaller

import scala.concurrent.duration._
import scala.io.StdIn

object JsonImplicits extends DefaultJsonProtocol {
  implicit val healthFormat = jsonFormat2(Health)
}

object MyApplication {
  val host = "localhost"
  val port = 8080

  def main(args: Array[String]): Unit = {

    implicit val system = ActorSystem("simple-rest-system")

    // Something to do with flows
    implicit val materializer = ActorMaterializer()

    // A reference to a specific thread pool
    // You can configure thread pool options through it
    // It is the engine that executes the actors
    implicit val executionContext = system.dispatcher

    val requestHandler = system.actorOf(RequestHandler.props(), "requestHandler")

    //Define the route
    val route : Route = {
      implicit val timeout = Timeout(20 seconds)
      import JsonImplicits._
      import spray.httpx.SprayJsonSupport._

      path("health") {
        get {
          onSuccess(requestHandler ? GetHealthRequest) {
            case response: HealthResponse =>
              complete(StatusCodes.OK, s"Everything is ${response.health.status}!")
            case _ =>
              complete(StatusCodes.InternalServerError)
          }
        }
      } ~ post {
        // Entity extracts the body of the POST request and then converts it into a
        // Health object

        entity(as[Health]) { statusReport =>
          onSuccess(requestHandler ? SetStatusRequest(statusReport)) {
            case response: HealthResponse =>
              complete(StatusCodes.OK,s"Posted health as ${response.health.status}!")
            case _ =>
              complete(StatusCodes.InternalServerError)
          }
        }
      }
    }

    //Start up and listen for requests
    val bindingFuture = Http().bindAndHandle(route, host, port)
    println(s"Waiting for requests at http://$host:$port/...\nHit RETURN to terminate")
    StdIn.readLine()

    //Shutdown
    bindingFuture.flatMap(_.unbind())
    system.terminate()
  }
}

0 个答案:

没有答案