亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解如何配置Spring Batch批處理失敗重試機(jī)制

 更新時(shí)間:2023年06月30日 14:09:15   作者:陸理手記  
這篇文章主要來(lái)和大家一起探討一下如何在Spring批處理框架中配置重試邏輯,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

1. 引言

默認(rèn)情況下,Spring批處理作業(yè)在執(zhí)行過(guò)程中出現(xiàn)任何錯(cuò)誤都會(huì)失敗。然而有些時(shí)候,為了提高應(yīng)用程序的彈性,我們就需要處理這類間歇性的故障。 在這篇短文中,我們就來(lái)一起探討 如何在Spring批處理框架中配置重試邏輯。

2. 簡(jiǎn)單舉例

假設(shè)有一個(gè)批處理作業(yè),它讀取一個(gè)CSV文件作為輸入:

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

然后,它通過(guò)訪問(wèn)REST端點(diǎn)來(lái)處理每條記錄,獲取用戶的 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;
    }
    ...
}

最后,它生成并輸出一個(gè)合并的XML:

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

3. ItemProcessor 中添加重試

現(xiàn)在假設(shè),如果到REST端點(diǎn)的連接由于某些網(wǎng)絡(luò)速度慢而超時(shí),該怎么辦?如果發(fā)生這種情況,則我們的批處理工作將失敗。

在這種情況下,我們希望失敗的 item 處理重試幾次。因此,接下來(lái)我將批處理作業(yè)配置為:在出現(xiàn)故障時(shí)執(zhí)行最多三次重試

@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();
}

這里調(diào)用了 faultTolerant() 來(lái)啟用重試功能。另外,我們使用 retry 和 retryLimit 分別定義符合重試條件的異常和 item 的最大重試次數(shù)。

4. 測(cè)試重試次數(shù)

假設(shè)我們有一個(gè)測(cè)試場(chǎng)景,其中返回 age 和 postCode 的REST端點(diǎn)關(guān)閉了一段時(shí)間。在這個(gè)測(cè)試場(chǎng)景中,我們只對(duì)前兩個(gè) API 調(diào)用獲取一個(gè) ConnectTimeoutException ,而第三個(gè)調(diào)用將成功:

@Test
public void whenEndpointFailsTwicePasses3rdTime_thenSuccess() throws Exception {
    FileSystemResource expectedResult = new FileSystemResource(EXPECTED_OUTPUT);
    FileSystemResource actualResult = new FileSystemResource(TEST_OUTPUT);
    when(httpResponse.getEntity())
      .thenReturn(new StringEntity("{ \"age\":10, \"postCode\":\"430222\" }"));
    //fails for first two calls and passes third time onwards
    when(httpClient.execute(any()))
      .thenThrow(new ConnectTimeoutException("Timeout count 1"))
      .thenThrow(new ConnectTimeoutException("Timeout count 2"))
      .thenReturn(httpResponse);
    JobExecution jobExecution = jobLauncherTestUtils
      .launchJob(defaultJobParameters());
    JobInstance actualJobInstance = jobExecution.getJobInstance();
    ExitStatus actualJobExitStatus = jobExecution.getExitStatus();
    assertThat(actualJobInstance.getJobName(), is("retryBatchJob"));
    assertThat(actualJobExitStatus.getExitCode(), is("COMPLETED"));
    AssertFile.assertFileEquals(expectedResult, actualResult);
}

在這里,我們的工作成功地完成了。另外,從日志中可以明顯看出 第一條記錄 id=1234 失敗了兩次,最后在第三次重試時(shí)成功了

19:06:57.742 [main] INFO  o.s.batch.core.job.SimpleStepHandler - Executing step: [retryStep]
19:06:57.758 [main] INFO  o.b.batch.service.RetryItemProcessor - Attempting to process user with id=1234
19:06:57.758 [main] INFO  o.b.batch.service.RetryItemProcessor - Attempting to process user with id=1234
19:06:57.758 [main] INFO  o.b.batch.service.RetryItemProcessor - Attempting to process user with id=1234
19:06:57.758 [main] INFO  o.b.batch.service.RetryItemProcessor - Attempting to process user with id=9999
19:06:57.773 [main] INFO  o.s.batch.core.step.AbstractStep - Step: [retryStep] executed in 31ms

同樣,看下另一個(gè)測(cè)試用例,當(dāng)所有重試次數(shù)都用完時(shí)會(huì)發(fā)生什么:

@Test
public void whenEndpointAlwaysFail_thenJobFails() throws Exception {
    when(httpClient.execute(any()))
      .thenThrow(new ConnectTimeoutException("Endpoint is down"));
    JobExecution jobExecution = jobLauncherTestUtils
      .launchJob(defaultJobParameters());
    JobInstance actualJobInstance = jobExecution.getJobInstance();
    ExitStatus actualJobExitStatus = jobExecution.getExitStatus();
    assertThat(actualJobInstance.getJobName(), is("retryBatchJob"));
    assertThat(actualJobExitStatus.getExitCode(), is("FAILED"));
    assertThat(actualJobExitStatus.getExitDescription(),
      containsString("org.apache.http.conn.ConnectTimeoutException"));
}

在這個(gè)測(cè)試用例中,在作業(yè)因 ConnectTimeoutException 而失敗之前,會(huì)嘗試對(duì)第一條記錄重試三次。

5. 使用XML配置重試

最后,讓我們看一下與上述配置等價(jià)的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>

6. 簡(jiǎn)單總結(jié)

在本文中,我們學(xué)習(xí)了如何在Spring批處理中配置重試邏輯,其中包括使用Java和XML配置。以及使用單元測(cè)試來(lái)觀察重試在實(shí)踐中是如何工作的。

到此這篇關(guān)于詳解如何配置Spring Batch批處理失敗重試機(jī)制的文章就介紹到這了,更多相關(guān)Spring Batch批處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot中@ConditionalOnProperty的使用及作用詳解

    SpringBoot中@ConditionalOnProperty的使用及作用詳解

    這篇文章主要介紹了SpringBoot中@ConditionalOnProperty的使用及作用詳解,@ConditionalOnProperty通過(guò)讀取本地配置文件中的值來(lái)判斷 某些 Bean 或者 配置類 是否加入spring 中,需要的朋友可以參考下
    2024-01-01
  • 簡(jiǎn)單了解Spring中常用工具類

    簡(jiǎn)單了解Spring中常用工具類

    這篇文章主要介紹了簡(jiǎn)單了解Spring中常用工具類,非常全面,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • 舉例詳解用Java實(shí)現(xiàn)web分頁(yè)功能的方法

    舉例詳解用Java實(shí)現(xiàn)web分頁(yè)功能的方法

    這篇文章主要介紹了舉例詳解用Java實(shí)現(xiàn)web分頁(yè)功能的方法,這種基本功能現(xiàn)一般通過(guò)Hibernate框架來(lái)完成,需要的朋友可以參考下
    2015-10-10
  • spring boot使用sonarqube來(lái)檢查技術(shù)債務(wù)

    spring boot使用sonarqube來(lái)檢查技術(shù)債務(wù)

    今天小編就為大家分享一篇關(guān)于spring boot使用sonarqube來(lái)檢查技術(shù)債務(wù),小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2018-12-12
  • 使用Java校驗(yàn)SQL語(yǔ)句的合法性五種解決方案

    使用Java校驗(yàn)SQL語(yǔ)句的合法性五種解決方案

    這篇文章主要介紹了如何用java校驗(yàn)SQL語(yǔ)句的合法性(提供五種解決方案),使用JDBC?API和JSqlParser庫(kù)、正則表達(dá)式、ANTLR解析器生成器或Apache?Calcite庫(kù)都可以實(shí)現(xiàn)校驗(yàn)SQL語(yǔ)句的合法性,需要的朋友可以參考下
    2023-04-04
  • 詳解Java HashMap實(shí)現(xiàn)原理

    詳解Java HashMap實(shí)現(xiàn)原理

    HashMap是基于哈希表的Map接口實(shí)現(xiàn),提供了所有可選的映射操作,并允許使用null值和null建,不同步且不保證映射順序。本文將記錄一下研究HashMap實(shí)現(xiàn)原理。
    2017-01-01
  • java:無(wú)法訪問(wèn)org.springframework.boot.SpringApplication

    java:無(wú)法訪問(wèn)org.springframework.boot.SpringApplication

    本文主要介紹了java:無(wú)法訪問(wèn)org.springframework.boot.SpringApplication,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2025-03-03
  • Spring的Bean注入解析結(jié)果BeanDefinition詳解

    Spring的Bean注入解析結(jié)果BeanDefinition詳解

    這篇文章主要介紹了Spring的Bean注入解析結(jié)果BeanDefinition詳解,BeanDefinition描述了一個(gè)bean實(shí)例,擁有屬性值、構(gòu)造參數(shù)值和具體實(shí)現(xiàn)的其他信息,其是一個(gè)bean的元數(shù)據(jù),xml中配置的bean元素會(huì)被解析成BeanDefinition對(duì)象,需要的朋友可以參考下
    2023-12-12
  • SpringBoot3整合郵件服務(wù)實(shí)現(xiàn)郵件發(fā)送功能

    SpringBoot3整合郵件服務(wù)實(shí)現(xiàn)郵件發(fā)送功能

    本文介紹了spring boot整合email服務(wù),實(shí)現(xiàn)發(fā)送驗(yàn)證碼,郵件(普通文本郵件、靜態(tài)資源郵件、附件郵件),文中通過(guò)代碼示例介紹的非常詳細(xì),堅(jiān)持看完相信對(duì)你有幫助,需要的朋友可以參考下
    2024-05-05
  • SPFA算法的實(shí)現(xiàn)原理及其應(yīng)用詳解

    SPFA算法的實(shí)現(xiàn)原理及其應(yīng)用詳解

    SPFA算法,全稱為Shortest?Path?Faster?Algorithm,是求解單源最短路徑問(wèn)題的一種常用算法,本文就來(lái)聊聊它的實(shí)現(xiàn)原理與簡(jiǎn)單應(yīng)用吧
    2023-05-05

最新評(píng)論