自定义注+切面控制方法执行步骤,执行过的方法不再执行
一、自定义注解================
@Target({ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface XXXTaskStep {
String taskName();
int taskStep();
}
二、方法执行步骤=================================
@Transactional(rollbackFor = Exception.class)
@XXXTaskStep (taskName = XXXConstants.Task.TASK_XXX, taskStep = 1)
public void method1(SciRequestDTO request) {
}
@Transactional(rollbackFor = Exception.class)
@XXXTaskStep (taskName = XXXConstants.Task.TASK_XXX, taskStep = 2)
public void method2(SciRequestDTO request) {
}
@Transactional(rollbackFor = Exception.class)
@XXXTaskStep (taskName = XXXConstants.Task.TASK_XXX, taskStep = 3)
public void method3(SciRequestDTO request) {
}
@Transactional(rollbackFor = Exception.class)
@XXXTaskStep (taskName = XXXConstants.Task.TASK_XXX, taskStep = 4)
public void method4(SciRequestDTO request) {
}
@Transactional(rollbackFor = Exception.class)
@XXXTaskStep (taskName = XXXConstants.Task.TASK_XXX, taskStep = 5)
public void method5(SciRequestDTO request) {
}
三、切面逻辑===================================
@Component
@Aspect
public class XXXTaskStepAspect {
@Around(“@annotation(annotation.XXXTaskStep)”)
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取目标方法
Method method = methodSignature.getMethod();
//获取方法注解
XXXTaskStep annotation = method.getAnnotation(PMPTaskStep.class);
ScheduleTaskDO scheduleTaskDO = DomainFactory.create(ScheduleTaskDO.class)
.setTaskName(annotation.taskName())
.setTradingDay(PmpDateUtils.atStartOfDay(new Date()));
// 按照创建时间获取最近的一条Task
ScheduleTaskDO latestTaskDO = scheduleTaskDO.selectTask()
.stream()
.max(Comparator.comparing(ScheduleTaskDO::getCreateTime))
.orElseThrow(IllegalArgumentException::new);
//获取最新的指定的步骤
int latestStep = latestTaskDO.getTaskStep();
// 获取Task的状态,如果status = 0,则是刚执行
int taskStatus = latestTaskDO.getTaskStatus();
// 判断是否需要执行该方法,如果表记录中的步骤小于方法上注解的步骤或任务状态是0初始化,则继续执行
if (0 == taskStatus || latestStep < annotation.taskStep()) {
try {
result = joinPoint.proceed();
scheduleTaskDO.setTaskStep(annotation.taskStep())
.setTaskStatus(StatusEnum.COMPLETE.getVal())
.updateTask();
} catch (Throwable throwable) {
scheduleTaskDO.setTaskStatus(StatusEnum.FAILED.getVal())
.setPmpTaskId(latestTaskDO.getPmpTaskId())
.setErrorMessage(throwable.toString())
.updateTask();
}
} else {
}
return result;
}
}