简体   繁体   English

重试 spring 批处理中的读取器

[英]Retrying reader in spring Batch

I have written a spring batch application and item reader is throwing exception.我写了一个 spring 批处理应用程序,并且项目阅读器抛出异常。 How do I retry item reader?如何重试项目阅读器? I h ave added @EnableRetry on application class and below is the reader code我在应用程序@EnableRetry上添加了@EnableRetry,下面是阅读器代码

@Bean
  @Retryable(include = { RuntimeException.class }, maxAttempts = 1000, backoff = @Backoff(delay = 0))
  public ItemReader<Student> reader() {
    return new InMemoryStudentReader();
  }

Below is the reader class下面是阅读器class

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

But even after this the reader is not retried and job fails但即使在此之后,读者也不会重试并且工作失败

You are adding @Retryable on a bean definition method.您在 bean 定义方法上添加@Retryable This method is only called at configuration time by Spring to create an instance of your bean and will unlikely fail.此方法仅在配置时由 Spring 调用以创建 bean 的实例,并且不太可能失败。

You should be adding the annotation on the read method of your reader which is called at runtime when the step is running and might throw an exception:您应该在阅读器的read方法上添加注释,该方法在步骤运行时在运行时调用,并可能引发异常:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM