我已经编写了一个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 {
...
}