【问题标题】:How to read large CSV file from azure blob in chunks using rest template如何使用 rest 模板从 azure blob 中读取大型 CSV 文件
【发布时间】:2022-11-13 07:29:20
【问题描述】:

我需要从 azure blob 读取大型 CSV 文件,处理记录并将这些记录存储到 Db 中。目前我正在使用休息模板来完成这个。对于小型文件,它工作正常。但是,对于大型文件,它会出现内存不足错误。

  1. 如何使用 rest 模板从 azure blob 读取大型 CSV 文件。
  2. 我需要分块读取数据。
  3. 处理数据块并将其插入数据库。

【问题讨论】:

  • 我们需要看代码

标签: java spring-boot azure-blob-storage resttemplate


【解决方案1】:

第一个提示:不要将文件加载到内存中。这就是为什么您会出现内存不足异常。相反,读取它缓冲。

如果您使用的是 Spring 的 RestTemplate,请像这样打开下载流:

InputStream fileDownloadUrlStream = new URL(downloadUrl).openStream();
return new BufferedInputStream(fileDownloadUrlStream);

但是您不应该真正使用 RestTemplate 。查看此 Jira issue。但是,您可以尝试使用此example 来完成它。 但也有一个 Azure 存储客户端,您可以将其添加到 Maven(或 Gradle)项目(检查最新版本)。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
    <version>12.3.0</version>
</dependency>

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-storage</artifactId>
    <version>8.6.3</version>
</dependency>

使用块是一个很好的方法。下面是如何使用分块 blob 客户端从 Azure 存储下载文件块的示例:

 String connectionString = getAzureBlobStorageConnectionKeyName(accountName);
 BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connectionString).buildClient();
 BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerId); 
 BlobClient blobClient = containerClient.getBlobClient(blobName);
 BlockBlobClient blockBlobClient = blobClient.getBlockBlobClient();
 blockBlobClient.downloadWithResponse(new FileOutputStream(file),
                                      new BlobRange(0L, downloadSize * 1024 * 1024), // convert chunk size to MB
                                      null,
                                      null,
                                      false,
                                      Duration.ofMinutes(1L),
                                      null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2019-06-10
    • 2019-04-15
    • 2022-01-19
    • 1970-01-01
    • 2014-11-15
    相关资源
    最近更新 更多