Retry重试机制

spring retry 重试机制


1.该重试需要引入jar包

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

2.使用@Retryable和@Recover注解

@Retryable注解
被注解的方法发生异常时会重试
value:指定发生的异常进行重试
include:和value一样,默认空,当exclude也为空时,所有异常都重试
exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
maxAttemps:重试次数,默认3
backoff:重试补偿机制,默认没有

@Backoff注解
delay:指定延迟后重试
multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒

@Recover
当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调

3.下面是test类

import com.ampmind.framework.service.exception.BizException;
import com.ampmind.framework.util.log.Logger;
import com.ampmind.framework.util.log.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * 测试重试机制的类
 *
 * @author Tonfu.Chia
 * @create 2017-07-26-下午1:51
 */
@EnableRetry
@Service
public class RetryService {
    private Logger logger = LoggerFactory.getLogger(RetryService.class);

    int count = 1;

    @Retryable(maxAttempts = 5, backoff = @Backoff(delay = 1000, multiplier = 5), include = CanNotGetLockException.class)
    public void service() throws CanNotGetLockException {
        logger.info("", "重试第" + (count++) + "次。。。。。。");
        throw new CanNotGetLockException("重试异常");
    }

    @Recover
    public void recoverMethod(CanNotGetLockException e) {
        logger.info("", "数据恢复方法" + (count++));
    }

    class CanNotGetLockException extends BizException {

        public CanNotGetLockException() {
        }

        public CanNotGetLockException(String message) {
            super(message);
        }

        public CanNotGetLockException(Throwable cause) {
            super(cause);
        }

        public CanNotGetLockException(String message, String bizId) {
            super(message, bizId);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值