前面的例子step都是線性的流程,這里我們提供一個非線性的流程,也就是根據不同的狀態做不同的流程step處理。萬一有天悔恨變得太現實太世故太麻木,說不定能從回憶中重拾隨興飛翔。
step非線性的流程
A step execution listener can change the exit status of a step. The job can then use the exit status for the transition decision to the next step。我們通過job傳遞參數來模擬不同的退出狀態,從而來驗證和加強非線性流程的學習。
一、在batch.xml中定義一個job
<!--一個非線性流程的job--> <job id="noLinerJob"> <step id="firstStep"> <tasklet transaction-manager="transactionManager" ref="firstStepTasklet"> <listeners> <listener ref="firstStepListener"/> </listeners> </tasklet> <next on="COMPLETED" to="completedStep"/> <next on="OWN STATUS" to="ownStatusStep"/> <next on="*" to="allStatusStep"/> </step> <step id="completedStep"> <tasklet ref="completedTasklet"/> </step> <step id="ownStatusStep"> <tasklet ref="ownStatusTasklet"/> </step> <step id="allStatusStep"> <tasklet ref="allStatusTasklet"/> </step> </job>
在step層面上的監聽器中會有不同的返回狀態,根據不同的狀態我們做不同的流程處理。比如如果是COMPLETED,我們就執行completedStep。如果是OWN STATUS(我們自定義的變量),就執行ownStatusStep。如果上述變量都沒有,那么我們執行正則匹配所有的allStatusStep。下面我們列出firstStepListener的定義與實現。
<bean id="firstStepListener" class="spring.batch.noLiner.FirstStepListener" scope="step"> <property name="status" value="#{jobParameters['status']}"/> </bean>
注意上述bean定義中的scope="step"是必須的,否則會報錯。它的實現類代碼如下
package spring.batch.noLiner; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.listener.StepExecutionListenerSupport; /** * @Author: huhx * @Date: 2017-11-02 下午 7:35 */ public class FirstStepListener extends StepExecutionListenerSupport { private String status; public void setStatus(String status) { this.status = status; } @Override public ExitStatus afterStep(StepExecution stepExecution) { if (status.equals("1")) { return new ExitStatus("OWN STATUS"); } else if (status.equals("2")) { return new ExitStatus("NO STATUS"); } return ExitStatus.COMPLETED; } }
至於ownStatusTasklet和completedTasklet以及allStatusTasklet的實現比較簡單,就是打印一句話。這里就不再列舉。以下是打印的結果。
// 當sttus= != '1' && sttus= != '2' first step tasklet. completed status. // 當sttus='1' first step tasklet. own status. // 當sttus='2' first step tasklet. all status.
關於batch status與 exit status的區別:
Spring Batch uses two concepts to represent the status of an execution: the batch sta- tus and the exit status. Both step execution and job execution have their own batch and exit statuses property. The batch status describes the status of the execution of a job or a step. The exit status represents the status of the job/step once the execution is finished.
二、關於上述的next,springbatch還提供了fail、stop與end
fail、stop與end的用法如下所示
<step id="firstStep"> <tasklet transaction-manager="transactionManager" ref="firstStepTasklet"> <listeners> <listener ref="firstStepListener"/> </listeners> </tasklet> <next on="COMPLETED" to="completedStep"/> <end on="OWN STATUS"/> <fail on="*"/> </step>
它們的說明如下
友情鏈接