谷歌云存储使用流而不是字节缓冲区-java



我使用以下代码:

    GcsService gcsService = GcsServiceFactory.createGcsService();
    GcsFilename filename = new GcsFilename(BUCKETNAME, fileName);
    GcsFileOptions options = new GcsFileOptions.Builder()
        .mimeType(contentType)
        .acl("public-read")
        .addUserMetadata("myfield1", "my field value")
        .build();
    @SuppressWarnings("resource")
    GcsOutputChannel outputChannel =
        gcsService.createOrReplace(filename, options);
    outputChannel.write(ByteBuffer.wrap(byteArray));
    outputChannel.close();

问题是,当我尝试存储视频文件时,我必须将文件存储在byteArray中,这可能会导致内存问题。

但我找不到任何接口可以对流执行同样的操作。

问题:

  1. 我应该担心appengine srv中的mem问题吗?还是他们能够在mem中保持1分钟的视频?

  2. 可以用流代替字节数组吗?怎样

  3. 我正在以byte[] byteArray = IOUtils.toByteArray(stream);的形式读取字节。我应该使用字节数组作为真正的缓冲区,只读取块并将其上传到GCS吗?我该怎么做?

可用内存量取决于您配置的appengine实例类型。如果可以的话,流式传输这些数据似乎是个好主意。

不确定GcsService api,但看起来您可以使用gcloud Storage api来做到这一点:https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-storage/src/main/java/com/google/cloud/storage/Storage.java

此代码可能有效(未经测试)。。。

final BlobInfo info = BlobInfo.builder(bucket.getBucketName(), "name").contentType("image/png").build();
final ReadableByteChannel src = Channels.newChannel(stream);
final WriteChannel dst = gcsStorage.writer(info);
fastChannelCopy(src, dst);
private void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (src.read(buffer) != -1) {
        buffer.flip();      // prepare the buffer to be drained
        dest.write(buffer); // write to the channel, may block
        // If partial transfer, shift remainder down
        // If buffer is empty, same as doing clear()
        buffer.compact();
    }
    // EOF will leave buffer in fill state
    buffer.flip();
    // make sure the buffer is fully drained.
    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

最新更新