1、编写项目中需要的处理类,缩略代码为以下步骤:
1.1、编写执行job类:
jobLauncher执行job是通过查找job的名称来执行的。
jobparams可自定义业务参数
@Service
public class PaymentCostStatisticsRunner {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job testJob;
public void doStart(Map<String, Object> args) {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("jobid", SnowFlakeIdGenerator.nextId())
.addString("type", args.get("type").toString())
.addString("currentTime", LocalDateTime.now().toString())
.toJobParameters();
jobLauncher.run(testJob, jobParameters);
}
}
1.2、编写job类:
最初遇到的问题及解决方法:
a、不会接收jobparams中的参数:可以通过监听器来接收
b、调用job执行reader时,每次调用,都不会执行我reader中写的判断方法,只会执行项目启动时的分支的方法:加上@StepScope注解,调用接口时,会再次执行reader方法,此时会进行判断。
@Configuration
@Slf4j
public class Jobs implements StepExecutionListener {
private String type;
/**
* 付款申请统计Job.
*
* @return Job
*/
@Bean
public Job testJob() {
return jobBuilderFactory.get("testJob")
.start(step1())
.next(step2())
.build();
}
@Bean
public Step step1() {
allpaymentList = new HashSet<>();
return stepBuilderFactory.get("step1")
.listener(this) //此处使用了监听器,方便获取之前jobparams中传入的参数
.<~>chunk(size) //此处size指的是每次读取并处理的数据条数
.reader(step1Reader())
.writer(step1Writer())
.build();
}
@Bean
public Step step2() {
costComposeMap = Maps.newHashMap();
return stepBuilderFactory.get("step2")
.<~>chunk(size)
.reader(step2Reader()) //这里只是给自己写个案例 和step1一样 实际的方法就不写了
.processor(step2Processor())
.writer(step2Writer())
.build();
}
@SneakyThrows
@Bean
@StepScope
public MyBatisCursorItemReader step1Reader() {
MyBatisCursorItemReader reader = new MyBatisCursorItemReader<BorrowExt>();
String queryId;
try {
if ("1".equals(type)) {
queryId = "xx.xxx.xx.selectAll";
log.info("此时执行了全量");
} else {
queryId = "xx.xxx.xx..selectByUpdateTime";
Map<String, LocalDate> params = Maps.newHashMap();
params.put("updateTime", computeDateUtil.computeDate());
reader.setParameterValues(params);
log.info("此时执行了增量");
}
reader.setSqlSessionFactory(sqlSessionFactory); //此处根据业务数据配置一个数据源
reader.setQueryId(queryId);
reader.afterPropertiesSet();
} catch (Exception e) {
log.info(String.valueOf(e));
}
return reader;
}
@Bean
public ItemWriter<PaymentExt> step1Writer() {
return items -> {
log.info("这里做一些写入处理");
};
}
//这里实现了step监听器的方法
@Override
public void beforeStep(StepExecution stepExecution) {
//获取到jobParams中的参数
type = stepExecution.getJobExecution().getJobParameters().getString("type");
log.info("监听type为:{}", type);
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}