在玩akka-http实验1.0-M2时,我试图创建一个简单的Hello世界示例。
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
答案 0 :(得分:7)
通过研究,我能够理解缺少Execution Context
的问题。要解决这个问题,我需要包含这个:
implicit val executionContext = system.dispatcher
展望akka/http/marshalling/ToResponseMarshallable.scala
我看到ToResponseMarshallable.apply
需要它返回Future[HttpResponse]
。
此外,在akka/http/server/RoutingSetup.scala
中,RoutingSetup.apply
需要它。
可能是akka团队只需要添加更多@implicitNotFound
s。我在direct use of Futures in Akka和spray Marshaller for futures not in implicit scope after upgrading to spray 1.2
答案 1 :(得分: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()
}