最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring框架中一個(gè)有用的小組件之Spring Retry組件詳解

 更新時(shí)間:2021年07月23日 09:15:50   作者:碼農(nóng)熊貓  
Spring Retry 是從 Spring batch 中獨(dú)立出來(lái)的一個(gè)功能,主要實(shí)現(xiàn)了重試和熔斷,對(duì)于那些重試后不會(huì)改變結(jié)果,毫無(wú)意義的操作,不建議使用重試,今天通過(guò)本文給大家介紹Spring Retry組件詳解,感興趣的朋友一起看看吧

1、概述

Spring Retry 是Spring框架中的一個(gè)組件,
它提供了自動(dòng)重新調(diào)用失敗操作的能力。這在錯(cuò)誤可能是暫時(shí)發(fā)生的(如瞬時(shí)網(wǎng)絡(luò)故障)的情況下很有幫助。

在本文中,我們將看到使用Spring Retry的各種方式:注解、RetryTemplate以及回調(diào)。

2、Maven依賴

讓我們首先將spring-retry依賴項(xiàng)添加到我們的pom.xml文件中:

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.2.5.RELEASE</version>
</dependency>

我們還需要將Spring AOP添加到我們的項(xiàng)目中:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>

可以查看Maven Central來(lái)獲取最新版本的spring-retry
spring-aspects 依賴項(xiàng)。

3、開啟Spring Retry

要在應(yīng)用程序中啟用Spring Retry,我們需要將@EnableRetry注釋添加到我們的@Configuration類:

@Configuration
@EnableRetry
public class AppConfig { ... }

4、使用Spring Retry

4.1、@Retryable而不用恢復(fù)

我們可以使用@Retryable注解為方法添加重試功能:

@Service
public interface MyService {
    @Retryable(value = RuntimeException.class)
    void retryService(String sql);

}

在這里,當(dāng)拋出RuntimeException時(shí)嘗試重試。

根據(jù)@Retryable的默認(rèn)行為,重試最多可能發(fā)生3次,重試之間有1秒的延遲。

4.2、@Retryable@Recover

現(xiàn)在讓我們使用@Recover注解添加一個(gè)恢復(fù)方法:

@Service
public interface MyService {
    @Retryable(value = SQLException.class)
    void retryServiceWithRecovery(String sql) throws SQLException;
        
    @Recover
    void recover(SQLException e, String sql);
}

這里,當(dāng)拋出SQLException時(shí)重試會(huì)嘗試運(yùn)行。 當(dāng)@Retryable方法因指定異常而失敗時(shí),@Recover注解定義了一個(gè)單獨(dú)的恢復(fù)方法。

因此,如果retryServiceWithRecovery方法在三次嘗試之后還是拋出了SQLException,那么recover()方法將被調(diào)用。

恢復(fù)處理程序的第一個(gè)參數(shù)應(yīng)該是Throwable類型(可選)和相同的返回類型。其余的參數(shù)按相同順序從失敗方法的參數(shù)列表中填充。

4.3、自定義@Retryable的行為

為了自定義重試的行為,我們可以使用參數(shù)maxAttemptsbackoff

@Service
public interface MyService {
    @Retryable( value = SQLException.class, 
      maxAttempts = 2, backoff = @Backoff(delay = 100))
    void retryServiceWithCustomization(String sql) throws SQLException;
}

這樣最多將有兩次嘗試和100毫秒的延遲。

4.4、使用Spring Properties

我們還可以在@Retryable注解中使用properties。

為了演示這一點(diǎn),我們將看到如何將delaymaxAttempts的值外部化到一個(gè)properties文件中。

首先,讓我們?cè)诿麨?code>retryConfig.properties的文件中定義屬性:

retry.maxAttempts=2
retry.maxDelay=100

然后我們指示@Configuration類加載這個(gè)文件:

@PropertySource("classpath:retryConfig.properties")
public class AppConfig { ... }
// ...

最后,我們可以在@Retryable的定義中注入retry.maxAttemptsretry.maxDelay的值:

@Service 
public interface MyService { 
  @Retryable( value = SQLException.class, maxAttemptsExpression = "${retry.maxAttempts}",
            backoff = @Backoff(delayExpression = "${retry.maxDelay}")) 
  void retryServiceWithExternalizedConfiguration(String sql) throws SQLException; 
}

請(qǐng)注意,我們現(xiàn)在使用的是maxAttemptsExpressiondelayExpression而不是maxAttemptsdelay。

5、RetryTemplate

5.1、RetryOperations

Spring Retry提供了RetryOperations接口,它提供了一組execute()方法:

public interface RetryOperations {
    <T> T execute(RetryCallback<T> retryCallback) throws Exception;

    ...
}

execute()方法的參數(shù)RetryCallback,是一個(gè)接口,可以插入需要在失敗時(shí)重試的業(yè)務(wù)邏輯:

public interface RetryCallback<T> {
    T doWithRetry(RetryContext context) throws Throwable;
}

5.2、RetryTemplate配置

RetryTemplateRetryOperations的一個(gè)實(shí)現(xiàn)。

讓我們?cè)?code>@Configuration類中配置一個(gè)RetryTemplate的bean:

@Configuration
public class AppConfig {
    //...
    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
		
        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(2000l);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(2);
        retryTemplate.setRetryPolicy(retryPolicy);
		
        return retryTemplate;
    }
}

這個(gè)RetryPolicy確定了何時(shí)應(yīng)該重試操作。

其中SimpleRetryPolicy定義了重試的固定次數(shù),另一方面,BackOffPolicy用于控制重試嘗試之間的回退。

最后,FixedBackOffPolicy會(huì)使重試在繼續(xù)之前暫停一段固定的時(shí)間。

5.3、使用RetryTemplate

要使用重試處理來(lái)運(yùn)行代碼,我們可以調(diào)用retryTemplate.execute()方法:

retryTemplate.execute(new RetryCallback<Void, RuntimeException>() {
    @Override
    public Void doWithRetry(RetryContext arg0) {
        myService.templateRetryService();
        ...
    }
});

我們可以使用lambda表達(dá)式代替匿名類:

retryTemplate.execute(arg0 -> {
    myService.templateRetryService();
    return null;
});

6、監(jiān)聽器

監(jiān)聽器在重試時(shí)提供另外的回調(diào)。我們可以用這些來(lái)關(guān)注跨不同重試的各個(gè)橫切點(diǎn)。

6.1、添加回調(diào)

回調(diào)在RetryListener接口中提供:

public class DefaultListenerSupport extends RetryListenerSupport {
    @Override
    public <T, E extends Throwable> void close(RetryContext context,
      RetryCallback<T, E> callback, Throwable throwable) {
        logger.info("onClose");
        ...
        super.close(context, callback, throwable);
    }

    @Override
    public <T, E extends Throwable> void onError(RetryContext context,
      RetryCallback<T, E> callback, Throwable throwable) {
        logger.info("onError"); 
        ...
        super.onError(context, callback, throwable);
    }

    @Override
    public <T, E extends Throwable> boolean open(RetryContext context,
      RetryCallback<T, E> callback) {
        logger.info("onOpen");
        ...
        return super.open(context, callback);
    }
}

openclose的回調(diào)在整個(gè)重試之前和之后執(zhí)行,而onError應(yīng)用于單個(gè)RetryCallback調(diào)用。

6.2、注冊(cè)監(jiān)聽器

接下來(lái),我們將我們的監(jiān)聽器(DefaultListenerSupport)注冊(cè)到我們的RetryTemplate bean:

@Configuration
public class AppConfig {
    ...

    @Bean
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        ...
        retryTemplate.registerListener(new DefaultListenerSupport());
        return retryTemplate;
    }
}

7、測(cè)試結(jié)果

為了完成我們的示例,讓我們驗(yàn)證一下結(jié)果:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
  classes = AppConfig.class,
  loader = AnnotationConfigContextLoader.class)
public class SpringRetryIntegrationTest {

    @Autowired
    private MyService myService;

    @Autowired
    private RetryTemplate retryTemplate;

    @Test(expected = RuntimeException.class)
    public void givenTemplateRetryService_whenCallWithException_thenRetry() {
        retryTemplate.execute(arg0 -> {
            myService.templateRetryService();
            return null;
        });
    }
}

從測(cè)試日志中可以看出,我們已經(jīng)正確配置了RetryTemplateRetryListener

2020-01-09 20:04:10 [main] INFO  c.p.s.DefaultListenerSupport - onOpen
2020-01-09 20:04:10 [main] INFO  c.pinmost.springretry.MyServiceImpl - throw RuntimeException in method templateRetryService()
2020-01-09 20:04:10 [main] INFO  c.p.s.DefaultListenerSupport - onError
2020-01-09 20:04:12 [main] INFO  c.pinmost.springretry.MyServiceImpl - throw RuntimeException in method templateRetryService()
2020-01-09 20:04:12 [main] INFO  c.p.s.DefaultListenerSupport - onError
2020-01-09 20:04:12 [main] INFO  c.p.s.DefaultListenerSupport - onClose

8、結(jié)論

在本文中,我們看到了如何使用注解、RetryTemplate和回調(diào)監(jiān)聽器來(lái)使用Spring Retry。

原文地址:https://www.baeldung.com/spring-retry

到此這篇關(guān)于Spring框架中一個(gè)有用的小組件:Spring Retry的文章就介紹到這了,更多相關(guān)Spring Spring Retry組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring整合mybatis實(shí)現(xiàn)過(guò)程詳解

    Spring整合mybatis實(shí)現(xiàn)過(guò)程詳解

    這篇文章主要介紹了Spring整合mybatis實(shí)現(xiàn)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • SpringSession會(huì)話管理之Redis與JDBC存儲(chǔ)實(shí)現(xiàn)方式

    SpringSession會(huì)話管理之Redis與JDBC存儲(chǔ)實(shí)現(xiàn)方式

    本文將詳細(xì)介紹Spring Session的核心概念、特性以及如何使用Redis和JDBC來(lái)實(shí)現(xiàn)會(huì)話存儲(chǔ),幫助開發(fā)者構(gòu)建更加健壯和可擴(kuò)展的應(yīng)用系統(tǒng),希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • Java基礎(chǔ)入門總結(jié)之序列化和反序列化

    Java基礎(chǔ)入門總結(jié)之序列化和反序列化

    序列化是一種對(duì)象持久化的手段,普遍應(yīng)用在網(wǎng)絡(luò)傳輸、RMI等場(chǎng)景中,下面這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)入門總結(jié)之序列化和反序列化的相關(guān)資料,需要的朋友可以參考下
    2022-02-02
  • Java基于TCP方式的二進(jìn)制文件傳輸

    Java基于TCP方式的二進(jìn)制文件傳輸

    這篇文章主要為大家介紹了Java基于TCP方式的二進(jìn)制文件傳輸,一個(gè)基于Java Socket協(xié)議之上文件傳輸?shù)耐暾纠?,基于TCP通信完成,感興趣的小伙伴們可以參考一下
    2016-01-01
  • java使用xpath解析xml示例分享

    java使用xpath解析xml示例分享

    XPath基于XML的樹狀結(jié)構(gòu),提供在數(shù)據(jù)結(jié)構(gòu)樹中找尋節(jié)點(diǎn)的能力,下面是一小示例,需要的朋友可以參考下
    2014-03-03
  • SpringBoot自動(dòng)裝配原理詳解

    SpringBoot自動(dòng)裝配原理詳解

    這篇文章主要介紹了SpringBoot自動(dòng)裝配原理的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用SpringBoot框架,感興趣的朋友可以了解下
    2021-03-03
  • SpringBoot中使用Filter和Interceptor的示例代碼

    SpringBoot中使用Filter和Interceptor的示例代碼

    這篇文章主要介紹了SpringBoot中使用Filter和Interceptor的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • Java關(guān)鍵字this(動(dòng)力節(jié)點(diǎn)Java學(xué)院整理)

    Java關(guān)鍵字this(動(dòng)力節(jié)點(diǎn)Java學(xué)院整理)

    java中的this隨處可見,用法也多。通常情況下理解this關(guān)鍵字還是很容易的,但是在我初學(xué)的時(shí)候,有一個(gè)疑問卻一直不能很清晰的理解,現(xiàn)在慢慢的理解了,下面通過(guò)本文給大家記錄下,有需要的朋友參考下
    2017-03-03
  • Java工作環(huán)境的配置與Eclipse的安裝過(guò)程

    Java工作環(huán)境的配置與Eclipse的安裝過(guò)程

    這篇文章主要介紹了Java工作環(huán)境的配置與Eclipse的安裝過(guò)程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • 從JVM的內(nèi)存管理角度分析Java的GC垃圾回收機(jī)制

    從JVM的內(nèi)存管理角度分析Java的GC垃圾回收機(jī)制

    這篇文章主要介紹了從JVM的內(nèi)存管理角度分析Java的GC垃圾回收機(jī)制,帶有GC是Java語(yǔ)言的重要特性之一,需要的朋友可以參考下
    2015-11-11

最新評(píng)論

三原县| 舞阳县| 望谟县| 怀集县| 包头市| 佳木斯市| 西昌市| 台山市| 沐川县| 建水县| 佛学| 冀州市| 梁河县| 麻城市| 渑池县| 河北省| 濮阳市| 陵川县| 水城县| 西和县| 聂拉木县| 通海县| 鄢陵县| 竹溪县| 延庆县| 南乐县| 威海市| 和平区| 来凤县| 遂平县| 蒲城县| 邢台县| 北票市| 宜阳县| 龙陵县| 体育| 贡嘎县| 旬阳县| 土默特右旗| 阳泉市| 肇庆市|