如何重试Spring Batch FlatFileItemReader?

时间:2019-04-03 19:21:54

标签: spring-batch

我正尝试重试春季批处理FlatFileItemReader,但没有成功。

    FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>();

    Resource resource = new FileSystemResource("input/1-101-D-2017-212-volume-per-transaction.csv");

    try {
        resource.contentLength();
    } catch (IOException e) {
        e.printStackTrace();

    }

    reader.setResource(resource);
    reader.setRecordSeparatorPolicy(new BlankLineRecordSeparatorPolicy());

    DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>();
    reader.setLineMapper(lineMapper);
    reader.setStrict(false);
    reader.setLinesToSkip(NUMBER_OF_HEADER_LINES);

    DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
    reader.setSkippedLinesCallback(line -> tokenizer.setNames(line.split(",")));
    lineMapper.setLineTokenizer(tokenizer);

    lineMapper.setFieldSetMapper(new TransactionFieldSetMapper());
    reader.setLineMapper(lineMapper);

    return reader;

然后进入我的脚步

        .faultTolerant()
        .retryLimit(3)
        .retry(FileNotFoundException.class)

有人可以提示我如何重试吗?

1 个答案:

答案 0 :(得分:0)

希望它对您仍然有用,请参考以下示例,其中我使用FlatFileItemReader放置了重试阅读器的示例: https://github.com/jeronimogalicia/batch-retry-flatfile-item-reader

基本上,您必须使用@EnableRetry注释应用程序类,并像这样注释您的阅读器:

@Bean
@StepScope
@Retryable(include = { ItemStreamException.class }, maxAttempts = 5)
ItemReader<Player> loadRecordsReader() throws Exception {

    String filePath = "src/main/resources/players.csv";
    System.out.println("Loading records from "  + filePath + " try " + counter);

    FlatFileItemReader<Player> itemReader = new FlatFileItemReader<>();
    itemReader.setResource(new FileSystemResource(filePath));
    itemReader.setLinesToSkip(1);
    //DelimitedLineTokenizer defaults to comma as its delimiter
    DefaultLineMapper<Player> lineMapper = new DefaultLineMapper<>();
    lineMapper.setLineTokenizer(new DelimitedLineTokenizer());
    lineMapper.setFieldSetMapper(new PlayerFieldSetMapper());
    itemReader.setLineMapper(lineMapper);
    itemReader.open(new ExecutionContext());
    return itemReader;
}