Java 实现Spring批处理进度条-获取作业执行时的总行数

Java 实现Spring批处理进度条-获取作业执行时的总行数,java,spring,progress-bar,batch-processing,spring-batch,Java,Spring,Progress Bar,Batch Processing,Spring Batch,我有一个批处理作业,它使用HibernateCursorItemReader从数据库读取数据,使用自定义处理器处理结果,然后提交到另一个数据库 我想展示的是,相对于要处理的项目总数,已经处理了多少个项目 我曾尝试使用@beforeJob实现一个自定义的JobExecutionListener,以获取第一个表中的行数,然后对其进行比较 针对作业执行定期提交 有没有比使用作业执行侦听器更好的方法。是否可以在初始化或类似操作期间在hibernatecursorsoritemreader上设置值,在第一

我有一个批处理作业,它使用
HibernateCursorItemReader
从数据库读取数据,使用自定义处理器处理结果,然后提交到另一个数据库

我想展示的是,相对于要处理的项目总数,已经处理了多少个项目

我曾尝试使用
@beforeJob
实现一个自定义的
JobExecutionListener
,以获取第一个表中的行数,然后对其进行比较 针对
作业执行
定期提交

有没有比使用
作业执行
侦听器更好的方法。是否可以在初始化或类似操作期间在
hibernatecursorsoritemreader
上设置值,在第一次读取时获取表的总行数

工作

<batch:job id="SomeLongJob" job-repository="jobRepository" restartable="true">      
    <batch:listeners>
        <batch:listener ref="batchJobExecutionListener" />
    </batch:listeners>  
    <batch:step id="first1">
        <tasklet transaction-manager="hibernateTransactionManager">
            <chunk reader="hibernateItemReader"
                   processor="batchCustomProcessor"
                   writer="hibernateItemWriter"
                   skip-limit="0"
                   commit-interval="10">
            </chunk>
        </tasklet>
    </batch:step>
</batch:job>

阅读器

<bean id="hibernateItemReader"
    class="org.springframework.batch.item.database.HibernateCursorItemReader">
    <property name="queryString" value="from MyTable" />
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

作业开始前,获取要处理的项目总数,即行

BatchJobExecutionListener.class

public void beforeJob(JobExecution jobExecution) {      

    int total = dao.getTotalRows();
    jobExecution.getExecutionContext().put("JobComplete", total);

}
...
private JobExecution jobE;
...

public Long getProgress() {

    double jobComplete = (Double) jobE.
                            getExecutionContext().
                            get("jobComplete");
    double reads = 0;       
    for (StepExecution step : jobE.getStepExecutions()) {
        reads = reads + step.getReadCount();
    }
    return Math.round(reads / jobComplete * 100);
}
在作业执行期间,检索项目总数并与读取计数进行比较

JobWrapper.class

public void beforeJob(JobExecution jobExecution) {      

    int total = dao.getTotalRows();
    jobExecution.getExecutionContext().put("JobComplete", total);

}
...
private JobExecution jobE;
...

public Long getProgress() {

    double jobComplete = (Double) jobE.
                            getExecutionContext().
                            get("jobComplete");
    double reads = 0;       
    for (StepExecution step : jobE.getStepExecutions()) {
        reads = reads + step.getReadCount();
    }
    return Math.round(reads / jobComplete * 100);
}

为什么要将总计数存储到HibernateCursorItemReader中?Total rows count只是一个与读取器无关的信息,它使用侦听器(正如您所做的)或“first1”之前的额外步骤来获取行数并将其存储到jobExecutionContext中。您也可以安全地重新启动。