我正在尝试让一个基本的http客户端使用Akka HTTP将一些数据发布到REST API,但是我无法使以下代码工作:
def sendData(e : GenericEvent): Future[Either[(String,StatusCode),(GenericEvent,StatusCode)]] = {
val request = Marshal(e).to[RequestEntity]
val responseFuture: Future[HttpResponse] = request map { req =>
Source.single(HttpRequest(method = HttpMethods.POST, uri = s"/data-ingest", headers = List(auth), entity = req))
.via(dataIngestFlow)
.runWith(Sink.head)
}
responseFuture.flatMap { response =>
response.status match {
case OK => Unmarshal(response.entity).to[GenericEvent].map(Right(_, response.status))
case BadRequest => Future.successful(Left(s"$e.data: incorrect data", response.status))
case _ => Unmarshal(response.entity).to[String].flatMap { entity =>
val error = s"generic event ingest failed with status code ${response.status} and entity $entity"
logger.error(error)
Future.failed(new IOException(error))
}
}
}
我收到以下错误
polymorphic expression cannot be instantiated to expected type;
[error] found :
[T]akka.stream.scaladsl.Sink[T,scala.concurrent.Future[T]]
[error] required:
akka.stream.Graph[akka.stream.SinkShape[akka.http.scaladsl.model.HttpResponse],akka.http.scaladsl.model.HttpResponse]
[error] .runWith(Sink.head)
以下是dataIngestFlow的代码
val dataIngestFlow = Http().outgoingConnection(config.endpointUrl,config.endpointPort)
以下是服务器端的代码:
val routes = {
logRequestResult("akka-http-microservice") {
path("event-ingest") {
post {
entity(as[GenericEvent]) { eventIngest =>
log.info(s"Ingesting {} and publishing event to Kafka topic {}.", eventIngest.eventType,config.kafkaTopic)
kafka ! eventIngest
complete {
eventIngest
}
}~
entity(as[List[GenericEvent]]) { eventIngestList =>
eventIngestList.foreach{ eventIngest=>
log.info(s"Ingesting {} and publishing event List to Kafka topic {}.", eventIngest.eventType,config.kafkaTopic)
kafka ! eventIngest
}
complete {
eventIngestList
}
}
}
}
}
}
我尝试了另一个简单的客户端,它构建得很好但是在160个事件之后摄取停止,服务器不再接收任何事件。
答案 0 :(得分:-1)
我在您的示例中看到的第一个问题是RequestEntity
没有地图功能。因此,以下一行
val responseFuture: Future[HttpResponse] = request map { ...
不应该编译。
此外,如果request
实际上是一个Future(我在地图中推断),那么responseFuture
实际上是Future[Future[HttpResponse]]
类型,因为该流实现了它自己的Future。要解决此问题,您可以使用Future.flatMap
代替地图。即:
val responseFuture: Future[HttpResponse] = request flatMap { req =>
这是Futures中的monadic bind operation。