Spring Batch_实现Tasklet

Spring Batch_实现Tasklet

    Chunk-oriented processing is not the only way to process in a Step. What if a Step must consist as a simple stored procedure call? You could implement the call as an ItemReader and return null after the procedure finishes, but it is a bit unnatural since there would need to be a no-op ItemWriter. Spring Batch provides the TaskletStep for this scenario.


    The Tasklet is a simple interface that has one method, execute, which will be a called repeatedly by the TaskletStep until it either returns RepeatStatus.FINISHED or throws an exception to signal a failure. Each call to the Tasklet is wrapped in a transaction. Tasklet implementors might call a stored procedure, a script, or a simple SQL update statement. To create a TaskletStep, the 'ref' attribute of the <tasklet/> element should reference a bean defining a Tasklet object; no <chunk/> element should be used within the <tasklet/>:


http://docs.spring.io/spring-batch/trunk/reference/html/configureStep.html#exampleTaskletImplementation

如下的配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
< beans  xmlns = "http://www.springframework.org/schema/beans"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xmlns:batch = "http://www.springframework.org/schema/batch"
     xmlns:context = "http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
         http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
     <!--执行文件删除的任务 -->
     < batch:job  id = "taskletJob" >
         < batch:step  id = "deleteFilesInDir" >
             < batch:tasklet  ref = "fileDeletingTasklet"  />
         </ batch:step >
     </ batch:job >
 
     < bean  id = "fileDeletingTasklet"  class = "com.lyx.batch.FileDeletingTasklet" >
         < property  name = "directoryResource"  ref = "directoryResource"  />
     </ bean >
     < bean  id = "directoryResource"  class = "org.springframework.core.io.FileSystemResource" >
         < constructor-arg  value = "E:\workspace2\SpringBatch2\target"  />
     </ bean >
 
     <!--tomcat jdbc pool数据源配置 -->
     < bean  id = "dataSource"  class = "org.apache.tomcat.jdbc.pool.DataSource"
         destroy-method = "close" >
         < property  name = "poolProperties" >
             < bean  class = "org.apache.tomcat.jdbc.pool.PoolProperties" >
                 < property  name = "driverClassName"  value = "com.mysql.jdbc.Driver"  />
                 < property  name = "url"  value = "jdbc:mysql://localhost:3306/test"  />
                 < property  name = "username"  value = "root"  />
                 < property  name = "password"  value = "034039"  />
             </ bean >
         </ property >
     </ bean >
 
     <!-- spring batch 配置jobRepository -->
     < batch:job-repository  id = "jobRepository"
         data-source = "dataSource"  transaction-manager = "transactionManager"
         isolation-level-for-create = "REPEATABLE_READ"  table-prefix = "BATCH_"
         max-varchar-length = "1000"  />
     <!-- spring的事务管理器 -->
     < bean  id = "transactionManager"
         class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" >
         < property  name = "dataSource"  ref = "dataSource"  />
     </ bean >
 
     <!-- batch luncher -->
     < bean  id = "jobLauncher"
         class = "org.springframework.batch.core.launch.support.SimpleJobLauncher" >
         < property  name = "jobRepository"  ref = "jobRepository"  />
     </ bean >
</ beans >


类实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package  com.lyx.batch;
 
import  java.io.File;
 
import  org.springframework.batch.core.StepContribution;
import  org.springframework.batch.core.UnexpectedJobExecutionException;
import  org.springframework.batch.core.scope.context.ChunkContext;
import  org.springframework.batch.core.step.tasklet.Tasklet;
import  org.springframework.batch.repeat.RepeatStatus;
import  org.springframework.beans.factory.InitializingBean;
import  org.springframework.core.io.Resource;
import  org.springframework.util.Assert;
 
public  class  FileDeletingTasklet  implements  Tasklet, InitializingBean {
 
     private  Resource directory;
 
     /**
      * 实现execute方法
      */
     public  RepeatStatus execute(StepContribution contribution,
             ChunkContext chunkContext)  throws  Exception {
         File dir =  this .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( this .directory,  "directory must be set" );
     }
}


运行:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package  com.lyx.batch;
 
import  org.springframework.batch.core.ExitStatus;
import  org.springframework.batch.core.Job;
import  org.springframework.batch.core.JobExecution;
import  org.springframework.batch.core.JobParametersBuilder;
import  org.springframework.batch.core.JobParametersInvalidException;
import  org.springframework.batch.core.launch.JobLauncher;
import  org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import  org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import  org.springframework.batch.core.repository.JobRestartException;
import  org.springframework.context.ApplicationContext;
import  org.springframework.context.support.ClassPathXmlApplicationContext;
 
public  class  AppMain15 {
     public  static  void  main(String[] args)
             throws  JobExecutionAlreadyRunningException, JobRestartException,
             JobInstanceAlreadyCompleteException, JobParametersInvalidException {
 
         long  startTime = System.currentTimeMillis();  // 获取开始时间
 
         @SuppressWarnings ( "resource" )
         ApplicationContext context =  new  ClassPathXmlApplicationContext(
                 new  String[] {  "classpath:spring-batch-sample-tasklet.xml"  });
         JobParametersBuilder jobParametersBuilder =  new  JobParametersBuilder();
         Job job = (Job) context.getBean( "taskletJob" );
         JobLauncher launcher = (JobLauncher) context.getBean( "jobLauncher" );
         JobExecution result = launcher.run(job,
                 jobParametersBuilder.toJobParameters());
         ExitStatus es = result.getExitStatus();
         if  (es.getExitCode().equals(ExitStatus.COMPLETED.getExitCode())) {
             System.out.println( "任务正常完成" );
         else  {
             System.out.println( "任务失败,exitCode="  + es.getExitCode());
         }
 
         long  endTime = System.currentTimeMillis();  // 获取结束时间
         System.out.println( "程序运行时间: "  + (endTime - startTime) +  "ms" );
     }
}


=================END=================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值