1.依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Retry {
int times() default 3;
}
3.切面类
package com.example.per.aop;
import com.example.per.annotation.Retry;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Component
@Aspect
@Slf4j
public class RetryAspect {
@Pointcut(value = "@annotation(com.example.per.annotation.Retry)")
public void retryPoint() {
}
@Around(value = "retryPoint()")
public void around(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String methodName = method.getName();
Retry retry = method.getAnnotation(Retry.class);
int times = retry.times();
boolean isRetry = false;
for (int i = 1; i < times + 1; i++) {
try {
joinPoint.proceed();
isRetry = true;
} catch (Throwable throwable) {
log.info("method:{} run error:{}", methodName, throwable.getMessage());
log.info("3 seconds run retry, {} times", i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (isRetry) break;
}
}
}
4.task
package com.example.per.task;
import com.example.per.annotation.Retry;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestTask {
@Scheduled(cron = "0/5 * * * * ?")
@Retry
public void test20240326(){
int i = 10/0;
}
}
5.run