在Spring Batch中配置重試邏輯 - Baeldung

banq發表於2020-03-13

預設情況下,Spring批處理作業因執行期間引發的任何錯誤而失敗。但是,有時,我們可能需要提高應用程式的彈性來處理間歇性故障。在本快速教程中,我們將探索如何在Spring Batch框架中配置重試邏輯。
假設我們有一個批處理作業,它讀取輸入的CSV檔案:

username, userid, transaction_date, transaction_amount
sammy, 1234, 31/10/2015, 10000
john, 9999, 3/12/2015, 12321


然後,它透過點選REST端點以獲取使用者的age和postCode屬性來處理每條記錄:

public class RetryItemProcessor implements ItemProcessor<Transaction, Transaction> {
     
    @Override
    public Transaction process(Transaction transaction) throws IOException {
        log.info("RetryItemProcessor, attempting to process: {}", transaction);
        HttpResponse response = fetchMoreUserDetails(transaction.getUserId());
        //parse user's age and postCode from response and update transaction
        ...
        return transaction;
    }
    ...
}

最後,它生成一個合併的輸出XML:

<transactionRecord>
    <transactionRecord>
        <amount>10000.0</amount>
        <transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
        <userId>1234</userId>
        <username>sammy</username>
        <age>10</age>
        <postCode>430222</postCode>
    </transactionRecord>
    ...
</transactionRecord>


現在,如果由於某些網路緩慢而導致與REST端點的連線超時怎麼辦?如果是這樣,我們的批處理作業將失敗。
在這種情況下,我們希望重試失敗的專案兩次。因此,讓我們將批處理作業配置為在失敗的情況下最多執行三個重試:

@Bean
public Step retryStep(
  ItemProcessor<Transaction, Transaction> processor,
  ItemWriter<Transaction> writer) throws ParseException {
    return stepBuilderFactory
      .get("retryStep")
      .<Transaction, Transaction>chunk(10)
      .reader(itemReader(inputCsv))
      .processor(processor)
      .writer(writer)
      .faultTolerant()
      .retryLimit(3)
      .retry(ConnectTimeoutException.class)
      .retry(DeadlockLoserDataAccessException.class)
      .build();
}

在這裡,我們呼叫faultTolerant() 以啟用重試功能。此外,我們使用retry和retryLimit分別定義了符合重試條件的異常和項的最大重試計數。

看一下上述配置的XML等效配置:

<batch:job id="retryBatchJob">
    <batch:step id="retryStep">
        <batch:tasklet>
            <batch:chunk reader="itemReader" writer="itemWriter"
              processor="retryItemProcessor" commit-interval="10"
              retry-limit="3">
                <batch:retryable-exception-classes>
                    <batch:include class="org.apache.http.conn.ConnectTimeoutException"/>
                    <batch:include class="org.springframework.dao.DeadlockLoserDataAccessException"/>
                </batch:retryable-exception-classes>
            </batch:chunk>
        </batch:tasklet>
    </batch:step>
</batch:job>


 

相關文章