gpt4 book ai didi

java - 在 Spring 批处理中重试阅读器

转载 作者:行者123 更新时间:2023-12-02 08:39:56 25 4
gpt4 key购买 nike

我编写了一个 Spring Batch 应用程序,项目读取器抛出异常。如何重试项目阅读器?我已经添加了应用程序类上的 @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 {
...
}

关于java - 在 Spring 批处理中重试阅读器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61443326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com