spring batch 2: 搭建环境以及简单的Job

 
  

这节介绍如何使用spring batch。 Spring batch 默认为内存方式(HSQLDB),但是产品功能上需要进行监控job状态,以及异常情况。所以采用了存储到数据库(Mysql), 那么就需要为这部分建表,那么我们需要配置JobRepository去使用MySQL。建表脚本在 spring-batch-core jar包下的org.springframework.batch.core中。 一、搭建环境

    1. 引入jar包,采用Maven的方式引入。具体需要的包可以自己慢慢试。
        
            org.springframework.batch
            spring-batch-core
            ${spring.batch.version}
        
        
            org.springframework.batch
            spring-batch-admin-manager
            1.3.1.RELEASE
        
        
            org.springframework.batch
            spring-batch-infrastructure
            ${spring.batch.version}
        
        
            org.springframework.batch
            spring-batch-integration
            ${spring.batch.version}
        
2. 配置XML,如果集成spring boot则按官方文档就可以。

    a. 配置jobRepository
b. 配置jobLauncher

        
 
c. 配置job参数传递bean jobParameterBulider
d. 配置job异步多线程
二、 开始简单的job编写
    个人喜欢先写配置,再写业务逻辑上的东西。我们以提货提醒为例子,当然这个是去除了很多东西的例子,将就着看。

    
        
       
           
          
                 
                
            
        
    
    
    
        
            
                
                
                    
                
                
                
            
        
        
        
            
        
    

    


    
        
        
        
        
        
        
        
            
                
                
                
            
        
    
    
    
        
        

    
    
以上为配置文件,接下来一个个需要实现的类:
job启动
public class BatchRedExpireOpenIdJob {

    @Autowired
    private JobLauncher jobLauncher;
    @Autowired
    private Job redExpireOpenIdJob;
    @Autowired
    JobParametersBuilder jobParameterBulider;

    public boolean doExecuteTask(String jobId)
    {
        if(null == jobParameterBulider)
        {
            jobParameterBulider = SpringUtil.getBean("jobParameterBulider", JobParametersBuilder.class);
        }
        if(null == redExpireOpenIdJob)
        {
            redExpireOpenIdJob = SpringUtil.getBean("redExpireOpenIdJob",Job.class);
        }
        if(null == jobLauncher)
        {
            jobLauncher = SpringUtil.getBean("jobLauncher",JobLauncher.class);
        }
        //传递参数:jobId作为启动的job唯一标识
        jobParameterBulider.addDate("date", new Date());
        jobParameterBulider.addString("jobId", jobId);
        try {
            //启动job
            JobExecution execution =  jobLauncher.run(redExpireOpenIdJob,jobParameterBulider.toJobParameters());

        } catch (JobExecutionAlreadyRunningException e) {
            e.printStackTrace();
        } catch (JobRestartException e) {
            e.printStackTrace();
        } catch (JobInstanceAlreadyCompleteException e) {
            e.printStackTrace();
        } catch (JobParametersInvalidException e) {
            e.printStackTrace();
        }

        return true;
    }

}
pickUpPartitioner类

@Scope("step")
@Component("pickUpPartitioner")
public class pickUpPartitioner implements Partitioner {
    //参数来至于job启动的时候
    @Value("#{jobParameters['jobId']}")
    private String jobId;

    @Resource
    TaskSchedulerDao taskSchedulerDao;

    @Override
    public Map partition(int gridSize) {
        Map result = new HashMap();

        //昨天的订单日期
        String preOrderTime= "";
        //前天的订单日期

        TaskScheduler taskScheduler = taskSchedulerDao.selectByPrimaryKey(jobId);
        int days=0;
        int hours=0;
        if(null !=taskScheduler)
        {
            String hoursArry[] = taskScheduler.getTaskName().split("#");
            if(null != hoursArry && hoursArry.length>1)
            {
                hours = Integer.parseInt(hoursArry[0]);
            }
        }

        if(hours != 0)
        {
            days = hours/24;
        }

        String pre2OrderTime="";
        if(days==0){
            preOrderTime= DateUtil.dateToStr(DateUtil.getPreDay(), "yyyy-MM-dd");
        }
        else
            preOrderTime= DateUtil.dateToStr(DateUtil.getPreDay(-days), "yyyy-MM-dd");

        String sTime = preOrderTime+" 00:00:00";
        String eTime = preOrderTime+" 23:59:59";

        ExecutionContext value = new ExecutionContext();
        value.putString("sTime", sTime);
        value.putString("eTime", eTime);

        result.put("partition", value);

        return result;
    }

    public String getJobId() {
        return jobId;
    }

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
}
读取数据库与写入数据库就不再写,就是一般的sql语句。

处理过程pickUpProcessor
pickUpProcessor类

@Scope("step")
@Component("pickUpProcessor")
public class PickUpProcessor implements ItemProcessor {

    private static Map pickPointMap=new HashMap<>();
    //提货通知
    //获取参数jobId
    @Value("#{jobParameters['jobId']}")
    private String jobId;

    /**
    * 处理过程,返回类型与传入参数和ItemProcessor相同
    */
    @Override
    public NoticeInfo process( OrderVo order) throws Exception {
        if(null == order){
            return null;
        }
        Integer amOrPm = DateUtil.getAmPm();

        NoticeInfo noticeInfo = new NoticeInfo();
        noticeInfo.setId(UUIDUtil.generateUUID());

        noticeInfo.setStatus(APIConstant.status_enable);
        return noticeInfo;
    }
    //要获取JobID必须有get方法
    public String getJobId() {
        return jobId;
    }
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
}


作者:代码行间的无聊生活
链接:http://www.jianshu.com/p/46b341432262
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(spring学习,spring-batch)