第一个提示:不要将文件加载到内存中。这就是为什么您会出现内存不足异常。相反,读取它缓冲。
如果您使用的是 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);