6

在玩 akka-http 实验性 1.0-M2 时,我正在尝试创建一个简单的 Hello world 示例。

import akka.actor.ActorSystem
import akka.http.Http
import akka.http.model.HttpResponse
import akka.http.server.Route
import akka.stream.FlowMaterializer
import akka.http.server.Directives._

object Server extends App {

  val host = "127.0.0.1"
  val port = "8080"

  implicit val system = ActorSystem("my-testing-system")
  implicit val fm = FlowMaterializer()

  val serverBinding = Http(system).bind(interface = host, port = port)
  serverBinding.connections.foreach { connection ⇒
    println("Accepted new connection from: " + connection.remoteAddress)
    connection handleWith Route.handlerFlow {
      path("") {
        get {
          complete(HttpResponse(entity = "Hello world?"))
        }
      }
    }
  }
}

编译失败could not find implicit value for parameter setup: akka.http.server.RoutingSetup

另外,如果我改变

complete(HttpResponse(entity = "Hello world?"))

complete("Hello world?")

我得到另一个错误:type mismatch; found : String("Hello world?") required: akka.http.marshalling.ToResponseMarshallable

4

2 回答 2

7

通过研究,我能够理解缺少的问题Execution Context。为了解决这两个问题,我需要包括以下内容:

implicit val executionContext = system.dispatcher

调查akka/http/marshalling/ToResponseMarshallable.scala我看到ToResponseMarshallable.apply需要它返回一个Future[HttpResponse].

此外,在akka/http/server/RoutingSetup.scalaRoutingSetup.apply需要它。

可能是akka团队只需要添加更多@implicitNotFound的s。我能够在以下位置找到不准确但相关的答案:direct use of Futures in Akka and spray Marshaller for futures not in implicit scope after upgrade to spray 1.2

于 2015-01-14T11:12:27.163 回答
2

很好发现 - 这个问题在 Akka HTTP 1.0-RC2 中仍然存在,所以现在的代码必须看起来像这样(考虑到他们的 API 更改):

import akka.actor.ActorSystem
import akka.http.scaladsl.server._
import akka.http.scaladsl._
import akka.stream.ActorFlowMaterializer
import akka.stream.scaladsl.{Sink, Source}
import akka.http.scaladsl.model.HttpResponse
import Directives._
import scala.concurrent.Future

object BootWithRouting extends App {

  val host = "127.0.0.1"
  val port = 8080

  implicit val system = ActorSystem("my-testing-system")
  implicit val fm = ActorFlowMaterializer()
  implicit val executionContext = system.dispatcher

  val serverSource: Source[Http.IncomingConnection, Future[Http.ServerBinding]] =
    Http(system).bind(interface = host, port = port)

  serverSource.to(Sink.foreach {
    connection =>
      println("Accepted new connection from: " + connection.remoteAddress)
      connection handleWith Route.handlerFlow {
        path("") {
          get {
            complete(HttpResponse(entity = "Hello world?"))
          }
        }
      }
  }).run()
}
于 2015-05-07T10:17:47.447 回答