我需要使用到 java.util.zip.ZipOutputStream
以压缩文件存档响应。
未压缩的数据有几百兆字节,所以我想尽可能少地存储它。它来自 SQL 结果的序列化。
我看到使用 OutputStream
的示例使用 Enumerator.outputStream
返回分块结果:
但是当我阅读文档时,这些似乎是不明智的(强调我的)
Create an Enumerator of bytes with an OutputStream.
Not that calls to write will not block, so if the iteratee that is being fed to is slow to consume the input, the OutputStream will not push back. This means it should not be used with large streams since there is a risk of running out of memory.
显然,我不能使用那个。或者至少不是没有修改。
如何使用
OutputStream
创建响应(在这种情况下,一个 gzip 压缩的存档)同时确保只有部分内容会存储在内存中?我承认
InputStream
之间的区别s/OutputStream
s and Play的Enumerator
/Iteratee
范式,所以我希望会有一种特定的方式来生成我的源数据(SQL 结果的序列化),这样它就不会超过下载速度。我不知道它是什么。
最佳答案
一般来说,您不能安全地使用任何 OutputStream
使用 Enumerator/Iteratee 框架,因为 OutputStream
不支持非阻塞回推。但是,如果您可以控制写入 OutputStream
你可以一起破解类似的东西:
val baos = new ByteArrayOutputStream
val zos = new ZipOutputStream(baos)
val enumerator = Enumerator.generateM {
Future.successful {
if (moreDateToWrite) {
// Write data into zos
val r = Some(baos.toByteArray)
baos.reset()
r
} else None
}
}
如果您只需要压缩,请查看
Enumeratee
play.filters.gzip.Gzip
中提供的实例和 play.filters.gzip.GzipFilter
筛选。
关于scala - 如何在 Play 2.1 中使用带有分块响应的 OutputStreams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24718645/