春季重试阅读器

Retrying reader in spring Batch(春季重试阅读器)

本文介绍了春季重试阅读器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个Spring批处理应用程序,而项阅读器抛出了异常。 如何重试项目阅读器? 我已经添加了 @EnableRetry在应用程序类上,下面是阅读器代码

@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;
  }
}

但即使在此之后,也不会重试读取器,作业失败

推荐答案

您正在Bean定义方法上添加@Retryable。此方法仅在配置时由Spring调用以创建Bean的实例,并且不太可能失败。

您应该在读取器的read方法上添加批注,该方法在步骤运行时调用,可能会引发异常:

@Override
@Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
public Student read() throws Exception {
   ...
}

这篇关于春季重试阅读器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:春季重试阅读器

基础教程推荐