1.定义注解FlushRedis
@Target(ElementType.METHOD) // 注解用来修饰方法
@Retention(RetentionPolicy.RUNTIME) // 运行时
@Documented // 文档
public @interface FlushRedis {
}
2.使用注解
@Transactional(rollbackFor = Exception.class)
@Override
@FlushRedis
public void updateResGroupSwitch(AlarmDescDetailsDto request) {
// 业务逻辑
}
3.定义AOP切面
注解的功能是方法返回结果后自动执行某些代码
@Slf4j
@Aspect // 定义切面
@Component
public class FlushRedisAspect {
@Autowired
ResGroupDaoService resGroupDaoService;
@Autowired
AlarmRuleNewDaoService alarmRuleNewDaoService;
AlarmRuleNewConverter middleDataConvert = new AlarmRuleNewConverter();
AlarmRuleFlinkConverter converter = new AlarmRuleFlinkConverter();
@Pointcut("@annotation(delta.service.annotation.FlushRedis)") // 以应用了FlushRedis注解的为切面点
public void flushPointCut() {
}
@Before("flushPointCut()") // 切入点之前执行的
private void before() throws Exception {
}
@AfterReturning(pointcut = "flushPointCut()") // 注解修饰的方法返回结果后执行
private void afterReturning(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod(); // 获取修饰的方法
FlushRedis flushAnnotation = method.getAnnotation(FlushRedis.class); // 判断方法是否有FlushRedis注解
if (flushAnnotation == null) {
return;
}
// 获取切入点的方法的参数
Object[] args = joinPoint.getArgs();
try {
// 转成真正代码里的数据类型
AlarmDescDetailsDto alarmDescDetailsDto = (AlarmDescDetailsDto) args[0];
String resGroupCode = alarmDescDetailsDto.getDefinition();
// 执行业务逻辑
syncToRedis(resGroupCode);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void syncToRedis(String resGroupCode) {
// 事务提交后才执行某些动作,这是注册了一个同步的动作,提交完事务后自动改执行afterCommit方法
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
// 提交完事务后执行的动作
}
});
}
}
标签:FlushRedis,自定义,void,切面,注解,执行,public
From: https://www.cnblogs.com/PythonOrg/p/17090227.html