仅当文件是 Java 中的特定版本时,如何将文件上传到 GCS?

问题描述

我有一个使用GCS存储文件上传文件的案例。我想通过使用世代和先决条件 (x-goog-if-generation-match) 来避免竞争条件。

docs 中有一个解释说明如何做到这一点。

但是,我使用的是 Java API,并且文档仅显示 json/xml api。

解决方法

我找到的解决方案是这样做的:

    Blob object =
        storage.get(
            bucketName,filePath,Storage.BlobGetOption.fields(BlobField.GENERATION));
    long generation = object.getGeneration();

    // now do some other stuff that might cause race conditions...

    BlobId blobId = BlobId.of(bucketName,objectName,generation);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
    List<Storage.BlobWriteOption> blobWriteOptions = new ArrayList<>();
    blobWriteOptions.add(BlobWriteOption.generationMatch());
    
    // in case generation don't match this will throw "StorageException: 412 Precondition Failed"
    try (WriteChannel writer =
        storage.writer(blobInfo,blobWriteOptions.toArray(new BlobWriteOption[0]))) {
            writer.write(); // etc'
      }
    }