try {
runResult = template.execute(new RetryCallback
private int count = 0;
public Boolean doWithRetry(RetryContext context) throws Exception {
count++;
if(count < 5)
{
logger.info("exception happen" + count);
throw new Exception("exception happen" + count);
}
logger.info("here" + count);
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
if(runResult)
{
logger.info("成功");
}
else
{
logger.info("失败");
}
}
}
设计的情形为,前4次抛出异常,第五次执行成功,执行代码,我们得到如下的输出:
[plain]
INFO [com.test.springbatch.RetryTest] - exception happen1
INFO [com.test.springbatch.RetryTest] - exception happen2
INFO [com.test.springbatch.RetryTest] - exception happen3
INFO [com.test.springbatch.RetryTest] - exception happen4
INFO [com.test.springbatch.RetryTest] - here5
INFO [com.test.springbatch.RetryTest] - 成功
INFO [com.test.springbatch.RetryTest] - exception happen1
INFO [com.test.springbatch.RetryTest] - exception happen2
INFO [com.test.springbatch.RetryTest] - exception happen3
INFO [com.test.springbatch.RetryTest] - exception happen4
INFO [com.test.springbatch.RetryTest] - here5
INFO [com.test.springbatch.RetryTest] - 成功
第五次执行成功,符合我们设想的结果。
如果把重试次数改为4,会发生什么呢。
[java]
policy.setMaxAttempts(4);
policy.setMaxAttempts(4);执行结果如下:
[plain]
INFO [com.test.springbatch.RetryTest] - exception happen1
INFO [com.test.springbatch.RetryTest] - exception happen2
INFO [com.test.springbatch.RetryTest] - exception happen3
INFO [com.test.springbatch.RetryTest] - exception happen4
java.lang.Exception: exception happen4
at com.test.springbatch.RetryTest$1.doWithRetry(RetryTest.java:55)
at com.test.springbatch.RetryTest$1.doWithRetry(RetryTest.java:1)
at org.springframework.batch.retry.support.RetryTemplate.doExecute(RetryTemplate.java:240)
at org.springframework.batch.retry.support.RetryTemplate.execute(RetryTemplate.java:147)
at com.test.springbatch.RetryTest.main(RetryTest.java:46)
INFO [com.test.springbatch.RetryTest] - 失败
INFO [com.test.springbatch.RetryTest] - exception happen1
INFO [com.test.springbatch.RetryTest] - exception happen2
INFO [com.test.springbatch.RetryTest] - exception happen3
INFO [com.test.springbatch.RetryTest] - exception happen4
java.lang.Exception: exception happen4
at com.test.springbatch.RetryTest$1.doWithRetry(RetryTest.java:55)
at com.test.springbatch.RetryTest$1.doWithRetry(RetryTest.java:1)
at org.springframework.batch.retry.support.RetryTemplate.doExecute(RetryTemplate.java:240)
at org.springframework.batch.retry.support.RetryTemplate.execute(RetryTemplate.java:147)
at com.test.springbatch.RetryTest.main(RetryTest.java:46)
INFO [com.test.springbatch.RetryTest] - 失败
第4次发生了异常之后,马上就把异常抛给了我们自己定义的异常处理。
代码级的重试给了我们很高的灵活度,把某些比较容易出错的代码放入其中,能很好的增强我们代码的健壮性。