如何使用spring retry

需要在Spring中自动重新调用失败的操作吗?想了解更多请查看有关Spring Retry的本教程。

几天前,我注意到有一群人在询问如何使用Spring Retry。在我进入示例代码之前,让我快速解释Spring Retry背后的目的。Spring Retry提供了自动重新调用失败操作的功能。对瞬间错误(如瞬间网络故障)很有用。Spring Retry提供对流程和基于策略的行为的声明性控制,易于扩展和自定义。
你在这里可以找到完整的代码。

Maven Dependencies

<dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    </dependency>
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    </dependency>

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-test</artifactId>
        <scope>test</scope>
     </dependency>
</dependencies>

Enable Retry

package com.chrisshayan.example.springretry;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.EnableRetry;

@EnableRetry
@SpringBootApplication
public class SpringRetryApplication {

public static void main(String[] args) {
SpringApplication.run(SpringRetryApplication.class, args);
}

}

Using Retry With Annotations


package com.chrisshayan.example.springretry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
@Service
public class SampleRetryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleRetryService.class);
    private static int COUNTER = 0;
    @Retryable(
            value = {TypeOneException.class, TypeTwoException.class},
            maxAttempts = 4, backoff = @Backoff(2000))
    public String retryWhenException() throws TypeOneException, TypeTwoException {
        COUNTER++;
        LOGGER.info("COUNTER = " + COUNTER);
        if(COUNTER == 1)
            throw new TypeOneException();
        else if(COUNTER == 2)
            throw new TypeTwoException();
        else
            throw new RuntimeException();
    }
    @Recover
    public String recover(Throwable t) {
        LOGGER.info("SampleRetryService.recover");
        return "Error Class :: " + t.getClass().getName();
    }
}

为了使您的测试类起作用,重试需要在适当的上下文中。这是因为我们需要另一个包含重试的服务。以下就是:

package com.chrisshayan.example.springretry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SampleRetryClientService {
    @Autowired
    private SampleRetryService sampleRetryService;
    public String callRetryService() throws TypeOneException, TypeTwoException {
        return sampleRetryService.retryWhenException();
    }
}

Test Class

package com.chrisshayan.example.springretry;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SpringRetryApplicationTests {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringRetryApplicationTests.class);
    @Autowired
    private SampleRetryClientService client;
@Test
public void contextLoads() {
}
@Test
    public void sampleRetryService() {
        try {
            final String message = client.callRetryService();
            LOGGER.info("message = " + message);
        } catch (TypeOneException | TypeTwoException e) {
            e.printStackTrace();
        }
    }
}

console

2018-07-10 23:42:45.528  INFO 14583 --- [           main] c.c.e.springretry.SampleRetryService     : COUNTER = 1
2018-07-10 23:42:47.534  INFO 14583 --- [           main] c.c.e.springretry.SampleRetryService     : COUNTER = 2
2018-07-10 23:42:49.538  INFO 14583 --- [           main] c.c.e.springretry.SampleRetryService     : COUNTER = 3
2018-07-10 23:42:49.539  INFO 14583 --- [           main] c.c.e.springretry.SampleRetryService     : SampleRetryService.recover
2018-07-10 23:42:49.539  INFO 14583 --- [           main] c.c.e.s.SpringRetryApplicationTests      : message = Error Class :: java.lang.RuntimeException

Spring Retry中有更多功能,例如无状态重试,状态重试以及不同的重试策略和侦听器。你可以在这里阅读更多。

Spring Retry 是一个用于在失败情况下自动重试的库。它提供了一些注解和模板来简化重试逻辑的编写和配置。 要使用 Spring Retry,首先需要将其添加为项目的依赖项。在 Maven 项目中,可以通过在 pom.xml 文件中添加以下依赖项来实现: ``` <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.3.1</version> </dependency> ``` 然后,在需要进行重试的方法上添加 @Retryable 注解。该注解可以指定重试的次数、重试的异常类型以及可选的回退方法。例如: ```java import org.springframework.retry.annotation.Retryable; @Retryable(value = {CustomException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000)) public void retryMethod() throws CustomException { // 重试逻辑 } ``` 在上面的示例中,retryMethod() 方法将在捕获 CustomException 异常时进行最多三次重试。每次重试之间会等待 1000 毫秒。 最后,需要在 Spring 的配置类上添加 @EnableRetry 注解以启用重试功能。例如: ```java import org.springframework.context.annotation.Configuration; import org.springframework.retry.annotation.EnableRetry; @Configuration @EnableRetry public class AppConfig { // 配置类内容 } ``` 这样,Spring Retry 就会自动在发生异常时触发重试逻辑。 需要注意的是,Spring Retry 默认只会重试在方法内部抛出的异常,而不会重试外部异常(例如网络故障)。如果需要对外部异常进行重试,可以通过自定义 RetryPolicy 或使用 Spring 的 AspectJ 功能来实现。 希望这些信息能帮助到你使用 Spring Retry。如果有任何进一步的问题,请随时提问!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值