tasklet和chunk的区别

在spring batch 的步骤中,具体执行业务逻辑的代码放在tasklet中。

spring batch 提供了两种方式:

1、使用chunk实现标准的读、处理、写三种操作;

2、实现 tasklet 接口,并实现其 execute 方法。

一、chunk

先看看如何使用chunk来定义一个任务和步骤,代码如下:

<!-- 定义任务和步骤 -->
    <batch:job id="XXXJob" restartable="true" job-repository="jobRepository">
        <batch:step id="XXXStep">
            <batch:tasklet transaction-manager="transactionManager" >
                <batch:chunk reader="XXXReader"
                             writer="XXXWriter"
                             processor="XXXProcessor"
                             commit-interval="10">
                </batch:chunk>
            </batch:tasklet>
        </batch:step>
    </batch:job>

 

Chunk 典型地提供了标准的read、process、write三种操作,而且还有事务提交间隔、重试策略等。

Step、tasklet、chunk这三者的关系图如下:

从代码上也可看出,Chunk是定义在Tasklet里面的。

 

二、Tasklet

Tasklet定义一个步骤的示例,可直接参考官网给出来的代码。

1、首先定义一个实现Tasklet的类:

public class FileDeletingTasklet implements Tasklet, InitializingBean {
    private Resource directory;
    
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        File dir = directory.getFile();
        Assert.state(dir.isDirectory());
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            boolean deleted = files[i].delete();
            if (!deleted) {
                throw new UnexpectedJobExecutionException("Could not delete file " + files[i].getPath());
            }
        }
        return RepeatStatus.FINISHED;
     }
     
    public void setDirectoryResource(Resource directory) {
        this.directory = directory;
    }
        
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(directory, "directory must be set");
    }
}

2、XML配置:

<job id="taskletJob">
    <step id="deleteFilesInDir">
        <tasklet ref="fileDeletingTasklet"/>
    </step>
</job>

<beans:bean id="fileDeletingTasklet" class="org.springframework.batch.sample.tasklet.FileDeletingTasklet">
    <beans:property name="directoryResource">
        <beans:bean id="directory" class="org.springframework.core.io.FileSystemResource">
        <beans:constructor-arg value="target/test-outputs/test-dir" />
        </beans:bean>
    </beans:property>
</beans:bean>

三、两者区别

《Spring batch 批处理框架》一书中,提到Tasklet时如下描述:

 

提到Chunk的描述如下:

但这并没提到这两者的区别。

找到官方文档,在介绍Tasklet中有这么一段话:

Chunk-oriented processing is not the only way to process in a Step. What if a Step must consist of a

simple stored procedure call? You could implement the call as an ItemReader and return null after

the procedure finishes. However, doing so is a bit unnatural, since there would need to be a no-op

ItemWriter. Spring Batch provides the TaskletStep for this scenario.

 

Tasklet is a simple interface that has one method, execute, which is called repeatedly by the

TaskletStep until it either returns RepeatStatus.FINISHED or throws an exception to signal a failure.

Each call to a Tasklet is wrapped in a transaction. Tasklet implementors might call a stored

procedure, a script, or a simple SQL update statement.

这两段话,第一段描述了Tasklet的使用场景,第二段介绍Tasklet的一些使用细节。第一段话的翻译大致如下:

块处理不是处理步骤的唯一方法。 如果一个步骤必须包含一个简单的存储过程调用怎么办? 您可以将调用实现为ItemReader,并在过程完成后返回null。 但是,这样做有点不自然,因为将需要一个无任何操作的ItemWriter。 因此,Spring Batch为此场景提供了TaskletStep。 

看到这里,我一开始也没懂,但看了后面官网给的例子,也就大致明白了,官网在给Tasklet例子前有这么一段描述 :

Many batch jobs contain steps that must be done before the main processing begins in order to set

up various resources or after processing has completed to cleanup those resources. In the case of a

job that works heavily with files, it is often necessary to delete certain files locally after they have

been uploaded successfully to another location.

看了例子,发现这例子就是在一个Tasklet的execute方法中,对文件进行删除,没有对文件内容进行读、写操作 。

 

因此可以认为:

Tasklet 适用于该 Step 操作不需要读操作,或不需要写操作,或两者都不需要。

而Chunk则适用于典型的Read、Process、Write 操作。

 

官网的介绍中提到,如果你的步骤包含一个简单的存储过程调用(只存,不需要写),那就可以用Tasklet。当然,你也可以用Chunk,但这时,你的ItemWritter就是一个空实现,看着不自然。

而官网的Tasklet例子只对文件进行删除,不需要读、写文件的内容,因此用Tasklet也就非常合适了。

参考:

spring batch 官网文档:https://docs.spring.io/spring-batch/docs/4.2.x/reference/pdf/spring-batch-reference.pdf

发布了9 篇原创文章 · 获赞 2 · 访问量 5663
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章