本文介紹了春季重試閱讀器的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我已經(jīng)編寫(xiě)了一個(gè)Spring批處理應(yīng)用程序,而項(xiàng)閱讀器拋出了異常。
如何重試項(xiàng)目閱讀器?
我已經(jīng)添加了
@EnableRetry
在應(yīng)用程序類上,下面是閱讀器代碼
@Bean
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public ItemReader<Student> reader() {
return new InMemoryStudentReader();
}
下面是Reader類
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;
}
}
但即使在此之后,也不會(huì)重試讀取器,作業(yè)失敗
推薦答案
您正在Bean定義方法上添加@Retryable
。此方法僅在配置時(shí)由Spring調(diào)用以創(chuàng)建Bean的實(shí)例,并且不太可能失敗。
您應(yīng)該在讀取器的read
方法上添加批注,該方法在步驟運(yùn)行時(shí)調(diào)用,可能會(huì)引發(fā)異常:
@Override
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public Student read() throws Exception {
...
}
這篇關(guān)于春季重試閱讀器的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,