type mismatch with akka.http.scaladsl.server.Route

偶尔善良 提交于 2020-01-06 06:37:10

问题


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 or Route.asyncHandler a Route can be lifted into a handler Flow or async handler function to be used with a bindAndHandleXXX call from the Core Server API.

Note: There is also an implicit conversion from Route to Flow[HttpRequest, HttpResponse, Unit] defined in the RouteResult companion, which relies on Route.handlerFlow.

Therefore, you have at least three options:

  1. Call Route.handlerFlow:
...bindAndHandle(Route.handlerFlow(route(store)(logger)), ...)
  1. Import the methods in the Route companion object and do the same as above, except now you can drop the explicit reference to the Route object:
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Route._

...bindAndHandle(handlerFlow(route(store)(logger)), ...)
  1. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!