一、错误处理
默认情况下当任务出现异常时,SpringBatch会结束任务,当使相同的参数重启任务时,SpringBatch会去执行未执行的剩余任务。
@Bean
public Step error_step1() {
return stepBuilderFactory.get("error_step1").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
Map<String, Object> stepExecutioncontext= chunkContext.getStepContext().getStepExecutionContext();
if (stepExecutioncontext.containsKey("zyq")) { //第一次运行上下文不包含这个字段
system.out.println("error_step1 finish");
return RepeatStatus.FINISHED;
} else { // 第一次运行,存入字段,发生异常
log.info("error_step1 first run ....");
chunkContext.getStepContext().getStepExecution().getExecutionContext().put("zyq","111");
throw new RuntimeException(" error ------"); //发生了错误
}
}
}).build();
}
二、错误重试
当任务发生异常,不想直接报错,而是再次执行。
@Bean
public Step errorretry_step1() {
return stepBuilderFactory.get("chunk_step")
.<String, Integer>chunk(10) //表示每一次处理reader两条,reader/process/write
.reader(read()) //读取
.processor(processor()) //处理
.writer(write()) //写入
.faultTolerant() //开启容错
.retry(CustomRetryException.class) //捕获的异常,这个异常可以在reader,processor,writer抛出,重试针对的是异常
.retryLimit(5) //针对捕获的有异常进行重试次数
.build();
}
retry:指定出错的异常类型
retrylimit:reader、processor、writer总的次数不可以超过5次。
三、错误跳过
@Bean
public Step errorretry_step1() {
return stepBuilderFactory.get("errorretry_step")
.<String, Integer>chunk(2) //表示每一次处理reader两条,reader/process/write
.reader(read()) //读取
.processor(skip_processor()) //处理
.writer(write()) //写入
.faultTolerant()//开启容错
.skip(MySpringBatchException.class)//跳过的异常类型
.skipLimit(2)//针对捕获的有异常进行重试
.build();
}
faultTolerant:容错
skip:跳过的异常类型
skipLimit:跳过总的次数,包括reader、processor、writer
四、错误跳过监听器
@Bean
public Step errorretry_step1() {
return stepBuilderFactory.get("errorretry_step1")
.<String, Integer>chunk(2) //表示每一次处理reader两条,reader/process/write
.reader(read()) //读取
.processor(skip_processor()) //处理
.writer(write()) //写入
.faultTolerant()//开启容错
.skip(MySpringBatchException.class)
.skipLimit(2)
.listener(mySkipListener())
.build();
}
public SkipListener<String,Integer> mySkipListener() {
return new SkipListener<String, Integer>() {
@Override
public void onSkipInRead(Throwable throwable) { //读的时候发生的异常
}
@Override
public void onSkipInWrite(Integer integer, Throwable throwable) {//写的时候发生的异常
}
@Override
public void onSkipInProcess(String str, Throwable throwable) { //处理的时候发生的异常
log.info("被跳过的数据:"+str);
log.info("被跳过的异常:"+throwable.getMessage());
}
};
监听器;