【问题标题】:Spring Batch - Custom reader and writerSpring Batch - 自定义阅读器和编写器
【发布时间】:2018-08-15 05:57:32
【问题描述】:

下面是一个自定义的平面文件项目阅读器的代码,它可以读取多个项目

public class MultipleItemsFlatFileReader<T> implements ItemReader<List<T>>, ItemStream {

private FlatFileItemReader<T> reader;
private int fetchSize;

public void setReader(String readerName, String filePath, String[] headers, int[] includedFileds,
        Class<? extends T> c, int fetchSize) {
    this.reader = CustomFlatFileReader.getReader(readerName, filePath, headers, includedFileds, c);
    this.fetchSize = fetchSize;
}

@Override
public List<T> read() throws Exception{

    List<T> items = new ArrayList<>();

    for (int count = 0; count < this.fetchSize; count++) {
        T item = reader.read();

        if (item == null) {
            break;
        }

        items.add(item);
    }

    if (!items.isEmpty()) {
        return items;
    }

    return null;
}

@Override
public void open(ExecutionContext executionContext) {
    reader.open(executionContext);
}

@Override
public void update(ExecutionContext executionContext) {
    reader.update(executionContext);
}

@Override
public void close() {
    reader.close();
}

}

以下是自定义项目编写器的代码

public class MultipleItemsCompositeJdbcWriter<T> implements ItemWriter<List<T>> {

private List<JdbcBatchItemWriter<T>> delegates;

public void setDelegates(List<JdbcBatchItemWriter<T>> writers) {
    this.delegates = writers;
}

@Override
public void write(List<? extends List<T>> items) throws Exception {
    for (JdbcBatchItemWriter<T> writer: delegates) {
        for (List<T> item: items) { 
            writer.write(item);
        }
    }
}

}

我是春季批次的新手。这段代码正确吗?我可能会丢失任何用例吗?目前我的批处理作业按顺序执行,但将来可能会使用多线程和分区。

我需要在处理器中进行数据库查找。对多个项目进行查找比对单个项目进行查找要好。

【问题讨论】:

标签: spring-batch


【解决方案1】:

Is this code correct?

答案取决于您的工作规范。在您的情况下,看起来一个项目是平面文件中多个物理行的逻辑组。

对于读者,文档中的以下部分可以提供帮助:https://docs.spring.io/spring-batch/4.0.x/reference/html/common-patterns.html#multiLineRecords

此用例还有两个示例:

对于作者,您可以使用CompositeItemWriter 与多个作者一起编写项目。更多细节在这里:https://docs.spring.io/spring-batch/4.0.x/api/org/springframework/batch/item/support/CompositeItemWriter.html

【讨论】:

  • 嗨@Mahmoud Ben Hassine,我正在使用基于java的MultiResourceItemReader,如何阅读“,”和“|”使用相同的阅读器分隔 csv 文件???
  • @sashikanta 请提出一个单独的问题,我会尽力提供帮助。
  • 嗨@Mahmoud Ben Hassine,这里是这个问题的链接和我的代码。 stackoverflow.com/questions/62413263/…
猜你喜欢
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
相关资源
最近更新 更多