【问题标题】:How to write to Azure Blob with Spring Batch?如何使用 Spring Batch 写入 Azure Blob?
【发布时间】:2021-07-01 11:39:55
【问题描述】:

我正在尝试使用 Spring Batch 将逐行 csv 写入 Azure Blob。

自动装配 Azure 存储:

@Value("${azure.storage.ConnectionString}")
private String connectionString;

@Value("${azure.storage.container.name}")
private String containerName;


@Bean
@StepScope
public FlatFileItemWriter<Pojo> writer(
        @Value("#{stepExecutionContext['marketName']}") String marketName,
        @Value("#{jobParameters['startDate']}") String startDate,
        @Value("#{jobParameters['YYYY-MM']}") String yearMonth
) {
    // Create writer instance
    FlatFileItemWriter<Pojo> writer = new FlatFileItemWriter<>();

    String fullPath = yearMonth + "/" +  marketName + "/" +
            marketName + "_" + startDate;

    BlobContainerClient container = new BlobContainerClientBuilder()
            .connectionString(connectionString)
            .containerName(containerName)
            .buildClient();

    BlobClient blob = container.getBlobClient(fullPath);

    // Set output file location
    writer.setResource((Resource) blob);

    // All job repetitions should "append" to same output file
    writer.setAppendAllowed(true);

    // Name field values sequence based on object properties
    writer.setLineAggregator(new DelimitedLineAggregator<Pojo>() {
        {
            setDelimiter(",");
            setFieldExtractor(new BeanWrapperFieldExtractor<Pojo>() {
                {
                    setNames(new String[] {
                            "market",
                            "epsg",
                            "xbin",
                            "ybin",
                            "latitude",
                            "longitude",
                            "totalDownlinkVol",
                            "totalUplinkVol"
                    });
                }
            });
        }
    });
    return writer;
}

然后我得到错误:

org.springframework.beans.factory.BeanCreationException:在类路径资源 [com/example/dbreader/configuration/BatchConfig.class] 中定义名称为“scopedTarget.writer”的 bean 创建错误:通过工厂方法实例化 bean 失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 [org.springframework.batch.item.file.FlatFileItemWriter]:工厂方法“writer”抛出异常;嵌套异常是 java.lang.ClassCastException: com.azure.storage.blob.BlobClient 不能转换为 org.springframework.core.io.Resource

Spring 抱怨我无法将 Blob 转换为资源。

有人知道如何在 Spring Batch Writer 中指向 Azure Blob 存储吗?

谢谢,马库斯。

【问题讨论】:

  • 如何将所有内容写入本地.csv文件并在写入后将此文件上传到azure blob并在上传后删除文件?

标签: spring azure spring-batch azure-storage azure-blob-storage


【解决方案1】:

FlatFileItemWriter 需要 org.springframework.core.io.Resource 来写入数据。如果您使用的 API 未实现此接口,则无法与 FlatFileItemWriter 一起使用。您需要为 Azure 提供 Resource 实现或寻找实现它的库,例如 Azure Spring Boot Starter Storage client library for Java

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2023-01-22
  • 2020-11-07
  • 1970-01-01
  • 2016-06-04
  • 2015-02-09
相关资源
最近更新 更多