Spring Batch - 计算已处理的行数

dog*_*ght 7 spring rows count spring-batch

所以我正在创建一个Spring Batch作业来读取CSV文件以及包含不完整数据的某些行; 它检查,输出到行不完整的日志,并跳过.它工作得很好,除了在工作结束时我希望它记录它找到的不完整的行数.只是一些简单的事情,比如"X不完整的行被发现".

我用谷歌搜索并寻找解决方案,但没有找到任何真正的东西.

任何帮助表示赞赏,需要更多信息.

M. *_*num 10

Spring Batch本身会跟踪它读取,写入,处理的数量以及跳过的数量(对于每个数字).该信息存储在StepExecution.该StepExecution可以从访问StepExecutionListener.在这种情况下,该afterStep方法的实现就足够了.

public class SkippedItemStepExecutionListener extends StepExecutionListenerSupport {

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        int skipped = stepExecution.getSkipCount(); // Total for read+write+process
        // Log it to somewhere.        
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

参考指南中介绍了如何将其添加到作业/步骤中

链接

  1. StepExecution javadoc
  2. StepExecutionListener javadoc
  3. 监听器配置参考


dog*_*ght 7

管理来解决这个问题,这就是我如何做到的:

在ItemProcessor中,我添加了一个属性和一个方法,用于从流程方法中访问ExecutionContext,

private ExecutionContext executionContext;

@BeforeStep
public void beforeStep(StepExecution stepExecution)
{
    this.executionContext = stepExecution.getExecutionContext();
}
Run Code Online (Sandbox Code Playgroud)

...然后在process()方法中找到我要记录的其中一行时,我可以这样做,

this.executionContext.putInt( "i_ThoseRows", this.executionContext.getInt( "i_ThoseRows", 0 ) + 1 );
Run Code Online (Sandbox Code Playgroud)

最后,我向ItemProcessor添加另一个方法,在步骤结束时打印结果,

@AfterStep
public void afterStep(StepExecution stepExecution)
{
    System.out.println( "Number of 'Those rows': " + this.executionContext.getInt( "i_ThoseRows", 0 ) );
}
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助某人