Spring 批处理如何根据条件跳过整个文件

Spring batch how to skip entire file on condition

我有 Spring 读取一些文件并将其保存到数据库的批处理作业。如果我需要能够编写一些自定义条件并在不满足条件时跳过文件处理。我尝试扩展 ItemReader 并抛出异常,但它导致整个作业失败,而我需要作业继续迭代文件。

谢谢

看看org.springframework.batch.core.step.skip.SkipPolicy界面。我给你一个从Pro Spring Batch written by T. Minella

中提取的例子
import java.io.FileNotFoundException;
import org.springframework.batch.core.step.skip.SkipLimitExceededException;
import org.springframework.batch.core.step.skip.SkipPolicy;
import org.springframework.batch.item.ParseException;

public class FileVerificationSkipper implements SkipPolicy {

public boolean shouldSkip(Throwable exception, int skipCount) throws SkipLimitExceededException {

if(exception instanceof FileNotFoundException) {
       return false;
} else if(exception instanceof ParseException && skipCount <= 10) {
       return true;
} else {
       return false;
    }
  }
}

在您的 xml 文件中:

<step id="copyFileStep">
  <tasklet>
    <chunk reader="customerItemReader" writer="outputWriter"
commit-interval="10" skip-limit="10">
      <skippable-exception-classes>
        <include class="java.lang.Exception"/>
        <exclude class="org.springframework.batch.item.ParseException"/>
      </skippable-exception-classes>
    </chunk>
  </tasklet>
</step>

或者另一种方法可能是在您的工作开始时添加一个步骤,将您的输入文件分类到两个单独的文件夹中。在一个文件夹中,您将拥有所有错误的文件,而在另一个文件夹中,只剩下好的文件。

所以我最终扩展了 MultiResourceItemReader 并覆盖了 read() 方法。在将文件委托给实际的 ItemReader 之前,它验证条件并将文件传递给 reader 只有在条件通过的情况下,否则处理到下一个文件

覆盖 reader 的 doRead() 方法并抛出您的应用特定异常。 例如:

*CustomFlatFileItemReader
    @Override
    protected T doRead() throws Exception {
        T itemRead=null;
        try {
            itemRead=   super.doRead();
        } catch (FlatFileParseException e) {
            throw new MyException(e.getMessage(), e);
        }
    return itemRead;
}*

2。设置作业的 skipPolicy 以跳过 MyException。

*.skipPolicy((Throwable T, int skipCount) -> {
                    if (T instanceof MyException)
                        return true;
                    else
                        return false;
                }*