在 spring 批次中重试 reader
Retrying reader in spring Batch
我写了一个 spring 批处理应用程序,但项目 reader 抛出异常。
如何重试项目 reader?
我已经添加了
@EnableRetry
申请 class,下面是 reader 代码
@Bean
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public ItemReader<Student> reader() {
return new InMemoryStudentReader();
}
下面是readerclass
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;
}
}
但即使在这之后 reader 也没有重试,作业失败了
您要在 bean 定义方法上添加 @Retryable
。此方法仅在配置时由 Spring 调用以创建您的 bean 的实例并且不太可能失败。
您应该在 reader 的 read
方法上添加注释,当步骤为 运行 时在运行时调用该方法并可能引发异常:
@Override
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public Student read() throws Exception {
...
}
我写了一个 spring 批处理应用程序,但项目 reader 抛出异常。
如何重试项目 reader?
我已经添加了
@EnableRetry
申请 class,下面是 reader 代码
@Bean
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public ItemReader<Student> reader() {
return new InMemoryStudentReader();
}
下面是readerclass
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;
}
}
但即使在这之后 reader 也没有重试,作业失败了
您要在 bean 定义方法上添加 @Retryable
。此方法仅在配置时由 Spring 调用以创建您的 bean 的实例并且不太可能失败。
您应该在 reader 的 read
方法上添加注释,当步骤为 运行 时在运行时调用该方法并可能引发异常:
@Override
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public Student read() throws Exception {
...
}