问题
I've created a http server with akka http as follows:
import akka.actor.typed.{ActorRef, ActorSystem}
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Route
import com.sweetsoft.LoggerActor.Log
import akka.actor.typed.scaladsl.adapter._
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.model._
import com.sweetsoft._
import akka.http.scaladsl.server.Directives._
import akka.stream.typed.scaladsl.ActorMaterializer
import scala.concurrent.Future
object ProducerActor {
private val route: Option[ActorRef[ProducerMessage]] => Option[ActorRef[Log]] => Route
= store => logger =>
path("producer") {
post {
entity(as[ProducerMessage]) { msg =>
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
}
}
}
def create[A](store: Option[ActorRef[ProducerMessage]], logger: Option[ActorRef[Log]])
(implicit system: ActorSystem[A])
: Future[ServerBinding] = {
implicit val materializer = ActorMaterializer()
//Please log
Http()(system.toUntyped).bindAndHandle(route(store)(logger), getServerIp, getServerPort)
}
}
The compiler complains:
[error] /home/developer/scala/plugger/src/main/scala/com/sweetsoft/producer/ProducerActor.scala:35:56: type mismatch;
[error] found : akka.http.scaladsl.server.Route
[error] (which expands to) akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult]
[error] required: akka.stream.scaladsl.Flow[akka.http.scaladsl.model.HttpRequest,akka.http.scaladsl.model.HttpResponse,Any]
[error] Http()(system.toUntyped).bindAndHandle(route(store)(logger), getServerIp, getServerPort)
Do I forget to import any libraries?
回答1:
From the documentation:
Using
Route.handlerFlow
orRoute.asyncHandler
aRoute
can be lifted into a handlerFlow
or async handler function to be used with abindAndHandleXXX
call from the Core Server API.Note: There is also an implicit conversion from
Route
toFlow[HttpRequest, HttpResponse, Unit]
defined in theRouteResult
companion, which relies onRoute.handlerFlow
.
Therefore, you have at least three options:
- Call
Route.handlerFlow
:
...bindAndHandle(Route.handlerFlow(route(store)(logger)), ...)
- Import the methods in the
Route
companion object and do the same as above, except now you can drop the explicit reference to theRoute
object:
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Route._
...bindAndHandle(handlerFlow(route(store)(logger)), ...)
- Import
akka.http.scaladsl.server.RouteResult._
:
import akka.http.scaladsl.server.RouteResult._
...bindAndHandle(route(store)(logger), ...)
来源:https://stackoverflow.com/questions/57241885/type-mismatch-with-akka-http-scaladsl-server-route