Akka-http - 写入响应输出流 [英] Akka-http - write to response output stream

查看:49
本文介绍了Akka-http - 写入响应输出流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个大的制表符分隔文件作为对 HTTP GET 请求的响应.在我的路由中创建一些 Scala 对象,然后我想将这些对象的一些自定义表示写入输出流.

I need to create a large tab separated file as a response to HTTP GET request. In my route a create some Scala objects and then I want to write some custom representation of those objects to the Output Stream.

这不仅仅是序列化到制表符分隔而不是 JSON,因为我还需要创建一个带有列名的标题,所以恕我直言,这无法通过自定义封送处理来解决.

It is not just serialization to tab separated instead of JSON, because I need also to create a header with column names, so IMHO this can't be solved with custom marshaling.

那么我怎样才能从 HttpRequest 中获得一个 writer 或 outputstream?

So how can I get a writer or outputstream from HttpRequest?

类似的东西

 ~path("export") {
        get {
              val sampleExonRPKMs = exonRPKMService.getRPKMs(samples)
              val writer = HttpResponse().getWriter // this does not exists
              writeHeader(writer)
              ... // write objects tab separated
        }
   }

推荐答案

您可以使用可编组源完成 Akka HTTP 路由.如果您不想使用自定义编组器,您可以随时使用 Source[ByteString, _] 完成.请参阅文档更多信息.

You can complete an Akka HTTP route with a marshallable source. If you don't want to use custom marshallers, you can always complete with a Source[ByteString, _]. See the docs for more info.

您的路线看起来像

get {
  val sampleExonRPKMs = exonRPKMService.getRPKMs(samples)
  val headers: String = ???
  Source.single(headers).concat(Source(sampleExonRPKMs).map(_.toTSVLine)).intersperse("\n").map(ByteString.apply)
}

注意作为一个单独的问题:如果您正在处理大量数据,getRPKMs 调用将导致将所有数据加载到内存中.

Note as a separate issue: if you are dealing with large amounts of data, the getRPKMs call will result in loading all of it in memory.

这篇关于Akka-http - 写入响应输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆