获取一个从InputStream发布的Publisher\

huangapple go评论76阅读模式
英文:

Get an Publisher<ByteBuffer> from InputStream

问题

我刚刚升级了我的mongo-db-java-driver,现在方便的函数GridFSBucket.uploadFromStream已经不存在了。因此,我们现在有了

GridFSUploadPublisher<ObjectId> uploadFromPublisher(String filename, Publisher<ByteBuffer> source);

有什么方法可以将我的InputStream转换成Publisher<ByteBuffer>?Java驱动程序或Reactor中有任何实用函数吗?

英文:

I just upgraded my mongo-db-java-driver and now the handy function GridFSBucket.uploadFromStream has gone. Therefore we now got a

GridFSUploadPublisher&lt;ObjectId&gt; uploadFromPublisher(String filename, Publisher&lt;ByteBuffer&gt; source);

Any ideas how to convert my InputStream into an Publisher&lt;ByteBuffer&gt;? Is there any utilfunction in the java driver or Reactor?

答案1

得分: 2

在 Spring 框架中有一个工具可以将输入流转换为数据缓冲区流。并且可以直接将数据缓冲区映射为字节缓冲区。

Flux<ByteBuffer> byteBufferFlux = DataBufferUtils.readByteChannel(() -> Channels.newChannel(inputStream), DefaultDataBufferFactory.sharedInstance, 4096).map(DataBuffer::asByteBuffer);
英文:

There is a util in spring framework to convert input stream to data buffer flux. And it's direct to map data buffer as byte buffer.

Flux&lt;ByteBuffer&gt; byteBufferFlux = DataBufferUtils.readByteChannel(() -&gt; Channels.newChannel(inputStream), DefaultDataBufferFactory.sharedInstance, 4096).map(DataBuffer::asByteBuffer);

答案2

得分: 0

为了让它只是工作,可以读取流并将数据存储在byte[]数组中,然后稍后可以使用ByteBuffer.wrap(byte[])方法进行封装。
我查看了旧版MongoDB驱动程序的源代码,并发现流被用作实际流,所以在那时它并没有被偷偷地转换为ByteBuffer。

似乎没有方法可以将数据作为流来传输,现在除了将文件加载到内存中没有其他方法。我可以看出这在许多情况下可能是个问题,但也许我只是无法理解这种方法的某些方面。

英文:

To just make it work one could read stream and store data in byte[] array which later can be wrapped with ByteBuffer.wrap(byte[]) method.
I've looked into older MongoDB driver's source code and found stream to be used as actual stream, so it was not sneakily converted to ByteBuffer under the hood back then.

It seems there is no method to stream the data as it comes, there is no other way than to load file into memory now. I can see how it can be a problem in many scenarios, but maybe I just can't understand something about this approach.

huangapple
  • 本文由 发表于 2020年9月18日 04:20:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63945665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定