我已经编写了一个Spring批处理应用程序,项目读取器抛出异常。如何重试商品阅读器?我已经添加了@EnableRetry
在应用程序类上,以下为阅读器代码
@Bean
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public ItemReader<Student> reader() {
return new InMemoryStudentReader();
}
下面是阅读器类
public class InMemoryStudentReader implements ItemReader<Student> {
@Autowired
private JdbcTemplate jdbcTemplate;
private int nextStudentIndex;
private List<Student> studentData;
public InMemoryStudentReader() {
initialize();
}
private void initialize() {
Student s1 = new Student(1, "ABC");
Student s2 = new Student(2, "DEF");
Student s3 = new Student(3, "GHI");
studentData = Collections.unmodifiableList(Arrays.asList(s1, s2,s3));
nextStudentIndex = 0;
}
@Override
public Student read() throws Exception {
Student nextStudent = null;
if (nextStudentIndex < studentData.size()) {
int a =jdbcTemplate.queryForObject("SELECT id FROM val LIMIT 1", Integer.class);
if(a == 2) {
throw new RuntimeException("Exception");
}
nextStudent = studentData.get(nextStudentIndex);
nextStudentIndex++;
} else {
nextStudentIndex = 0;
}
return nextStudent;
}
}
但是即使在此之后,读者也不会重试并且作业失败
您正在在bean定义方法上添加@Retryable
。 Spring仅在配置时调用此方法以创建bean的实例,并且不太可能失败。
您应该在阅读器的read
方法上添加注释,该注释在步骤运行时会在运行时被调用,并可能引发异常:
@Override
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public Student read() throws Exception {
...
}