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 Cloud介绍 Part2: Spring Cloud与微服务
- Spring Boot 使用 Caching-EhCache
- Spring Boot 使用 Caching-Redis
- Spring Boot 使用异步消息服务-JMS(ActiveMQ)
- springmvc实现url路由功能
- spring aop 无法代理父类方法 的解决方法
- Spring MVC过滤器-超类 GenericFilterBean
- 一个jar包里的网站
- 一个jar包里的网站之文件上传
- 一个jar包里的网站之返回对媒体类型
- 那些年玩过的框架-spring mvc
- Spring和ThreadLocal
- Spring 参数处理|数据绑定(setParameter)
- Spring Boot 开发微服务
- Spring AOP动态代理-切面
- RestTemplate 发送文件
- Spring Security 权限控制原理《一》
- JAVA 设计模式 之 动态代理