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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章