【问题标题】:Retrying reader in spring Batch在春季批处理中重试阅读器
【发布时间】:2020-08-10 02:09:30
【问题描述】:

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

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

【问题讨论】:

标签: java spring spring-batch batch-processing


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多