Spring Batch需要跳过无效的xml记录

时间:2012-05-23 20:15:54

标签: xml spring-batch

我们有业务要求尽可能多地处理文件,然后移动

如果记录98中包含100条记录的文件中存在错误,我们希望能够处理该点并跳过文件的其余部分,然后转到下一个文件。

我们正在处理MultiResourcePartitioner中的文件。

<batch:step id="processXMLstep"> 
<batch:tasklet  transaction-manager="transactionManager">
<batch:chunk reader="myXmlItemReader" processor="myProcessor
   Writer="myDBWriter" commit-interval="100"  skip-limit="10000">
<batch:skippable-exception-classes>
<batch:include class="java.lang.Exception"/>
</batch:skippable-exception-classes> 
</batch:chunk>
<batch:listeners>
<batch:listener ref="myFileNameListener" /> 
</batch:listeners>
</batch:tasklet>
<batch:end on="FAILED"/>
</batch:step>

读者正在使用StaxEventItemReader。

我已将onProcessError(),onReadError(),onSkipInProcess(),onSkipInRead(),onSkipInWrite()和onWriteError()方法添加到侦听器。我可以看到代码触及OnReadError()方法(并且取决于XML错误,onSkipInRead()方法)。

我可以在OnReadError()中执行某些操作来强制作业只是跳过文件的其余部分并移动到下一个文件吗?

1 个答案:

答案 0 :(得分:2)

此处的问题与StaxEventItemReader中默认的doRead()方法抛出的异常有关。我们必须编写一个自定义版本来检查特定的XML异常,然后将其作为自定义异常抛出(在skippable-excpection-classes中使用该自定义异常)。

以下是自定义doRead()的示例:

    @Override
protected xmlObject doRead() throws CustomXmlException {
    try {
        return super.doRead();
    } catch (Exception e) {
        if (e instanceof DataAccessResourceFailureException) {
            Throwable cause = e.getCause();
            if (cause instanceof XMLStreamException) {
                throw new CustomXmlException(e.getMessage());
            }
        }
        if(e instanceof NonTransientResourceException) {
            e.printStackTrace();
        }
        e.printStackTrace();
        return null;
    }
}

这是xml中的步骤:

    <batch:step id="processXMLstep"> 
    <batch:tasklet  transaction-manager="transactionManager">
        <batch:chunk reader="myXmlItemReader" processor="myProcessor" 
                 writer="myWriter" commit-interval="100" skip-limit="10000">
            <batch:skippable-exception-classes>
                <batch:include class="gov.irs.saas.etl.exception.CustomXmlException" /> 
            </batch:skippable-exception-classes> 
        </batch:chunk>
        <batch:listeners>
            <batch:listener ref="myFileNameListener" /> 
        </batch:listeners>
    </batch:tasklet>
    <batch:end on="FAILED"/>
</batch:step>

这似乎解决了以前会导致作业崩溃的XML错误(缺少元素上的开始标记,以及缺少最后xml结束标记的截断文件)。