Scala 使用迭代器完成akka http响应

Scala 使用迭代器完成akka http响应,scala,serialization,akka-http,Scala,Serialization,Akka Http,我有一个mongodb查询结果的迭代器,我希望将这些结果流式传输到http响应,而不将整个结果集加载到内存中 是否可以使用迭代器而不是集合或将来完成akka http响应?请查看。它允许从Mongo集合创建一个源,如: val source: Source[Document, NotUsed] = MongoSource(numbersColl.find()) val rows: Future[Seq[Document]] = source.runWith(Sink.seq) 或者您可能希望

我有一个mongodb查询结果的迭代器,我希望将这些结果流式传输到http响应,而不将整个结果集加载到内存中

是否可以使用迭代器而不是集合或将来完成akka http响应?

请查看。它允许从Mongo集合创建一个源,如:

val source: Source[Document, NotUsed] = MongoSource(numbersColl.find())

val rows: Future[Seq[Document]] = source.runWith(Sink.seq)
或者您可能希望自己的源代码实现作为一个GraphStage,例如。

看看。它允许从Mongo集合创建一个源,如:

val source: Source[Document, NotUsed] = MongoSource(numbersColl.find())

val rows: Future[Seq[Document]] = source.runWith(Sink.seq)

或者,您可能希望自己的源代码实现作为一个GraphStage,例如。

给定数据的迭代器:

type Data = ???

val dataIterator : () => Iterator[Data] = ???
首先需要一个函数将
数据
转换为
ByteString
表示形式,以及表示形式的
内容类型
():

import akka.util.ByteString
import akka.http.scaladsl.model.ContentType    

val dataToByteStr : Data => ByteString = ???

//see akka.http.scaladsl.model.ContentTypes for possible values
val contentType : ContentType = ???
迭代器和转换器函数现在可用于创建HttpResponse,该函数将结果流回到http客户端,而无需在内存中保存整个数据集:

import akka.http.scaladsl.model.HttpEntity.{Chunked, ChunkStreamPart}
import akka.http.scaladsl.model.ResponseEntity    
import akka.stream.scaladsl.Source
import akka.http.scaladsl.model.HttpResponse

val chunks : Source[ChunkStreamPart,_] = 
  Source.fromIterator(dataIterator)
        .map(dataToByteStr)
        .map(ChunkStreamPart.apply)

val entity : ResponseEntity = Chunked.fromData(contentType, chunks)

val httpResponse : HttpResponse = HttpResponse(entity=entity)

注意:由于每次从
dataIterator
生成一个新的迭代器,您不必为每个传入请求创建一个新的
httpResponse
;相同的响应可用于所有请求。

给定数据的迭代器:

type Data = ???

val dataIterator : () => Iterator[Data] = ???
首先需要一个函数将
数据
转换为
ByteString
表示形式,以及表示形式的
内容类型
():

import akka.util.ByteString
import akka.http.scaladsl.model.ContentType    

val dataToByteStr : Data => ByteString = ???

//see akka.http.scaladsl.model.ContentTypes for possible values
val contentType : ContentType = ???
迭代器和转换器函数现在可用于创建HttpResponse,该函数将结果流回到http客户端,而无需在内存中保存整个数据集:

import akka.http.scaladsl.model.HttpEntity.{Chunked, ChunkStreamPart}
import akka.http.scaladsl.model.ResponseEntity    
import akka.stream.scaladsl.Source
import akka.http.scaladsl.model.HttpResponse

val chunks : Source[ChunkStreamPart,_] = 
  Source.fromIterator(dataIterator)
        .map(dataToByteStr)
        .map(ChunkStreamPart.apply)

val entity : ResponseEntity = Chunked.fromData(contentType, chunks)

val httpResponse : HttpResponse = HttpResponse(entity=entity)

注意:由于每次从
dataIterator
生成一个新的迭代器,您不必为每个传入请求创建一个新的
httpResponse
;相同的响应可用于所有请求。

我使用的是salat和casbah。我调用collection.aggregate(),然后多次映射{}结果,我使用salat和casbah。我调用collection.aggregate(),然后多次映射{}结果