您的位置:首页 > 编程语言 > Java开发

Retry重试机制

2017-09-26 09:59 127 查看

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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring retry 重试