需求场景
有时候业务上需要一个简单的重试机制,这个时候写try catch
递归的话容易增加代码复杂度。此时直接上spring
的Retryable aop
就OK
了.
代码demo
package com.felix.spring_cloud_one.service;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Service
public class RetryableService {
@Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 3))
public void retryable() {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("当前时间为:" + dateTimeFormatter.format(LocalDateTime.now()));
throw new RuntimeException("测试");
}
}
运行结果
来简单解释一下注解中几个参数的含义:
- value:抛出指定异常才会重试
- include:和value一样,默认为空,当exclude也为空时,默认所有异常
- exclude:指定不处理的异常
- maxAttempts:最大重试次数,默认3次
- backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;
- multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为2,则第一次重试为2秒(delay 指定时间),第二次为4(multiplier X delay)秒,第三次为8(3 X multiplier X delay)秒。