UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Java】GCSにjsonファイルをアップロードする

すでにSpring BootでGCSにjsonファイルをアップロードする機能を実装していて動作確認済みなのだが、のちのち見つけた下の公式ドキュメントの方法と微妙にやり方がちがったので、どちらがよいのかを調べた

ドキュメントは以下
cloud.google.com

実装したCloudStorageClientクラス

@Slf4j
@Component
public class CloudStorageClient {
  private final Storage service;
  private final StorageOptions storageOptions;

  public CloudStorageClient() {
    storageOptions = StorageOptions.getDefaultInstance();
    service = storageOptions.getService();
  }

  public void saveJson(String bucket, String directory, String file, String content) {
    String object = CloudStorageUtil.createObjectName(directory, file);
    try (WriteChannel writer =
        service.writer(
            BlobInfo.newBuilder(bucket, object)
                .setContentType(MediaType.APPLICATION_JSON_VALUE)
                .build())) {
      writer.write(StandardCharsets.UTF_8.encode(content));
    } catch (IOException e) {
      log.error(
          "Failed to save content to Google Cloud Storage.project=[{}], bucket=[{}], object=[{}], content=[{}]",
          storageOptions.getProjectId(),
          bucket,
          object,
          e);
    }
  }
}

違いはservice.create()で書き込むか、service.writer.write()で書き込むかという点

APIドキュメントを見たところ、createメソッドの説明欄に記載があった

Blob create(BlobInfo blobInfo, byte[] content, Storage.BlobTargetOption... options)

Creates a new blob. Direct upload is used to upload content. For large content, writer(com.google.cloud.storage.BlobInfo, com.google.cloud.storage.Storage.BlobWriteOption...) is recommended as it uses resumable upload. MD5 and CRC32C hashes of content are computed and used for validating transferred data. Accepts an optional userProject Storage.BlobGetOption option which defines the project id to assign operational costs. The content type is detected from the blob name if not explicitly set. Storage Parent 2.1.3 API

つまり、大きなコンテンツの場合はwriter使ってねと書いてある

なので、ドキュメント通りでもよいけど、実装した方がコンテンツが大きい場合に耐えられるでよさそう