以一个锁的加锁和释放为例
1、先定义注解
/**
* 锁切面
* @author fmj
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface VersionLockAOP {
}
2、然后定义切面类以及切点
/**
* 切面
*/
@Component
@Aspect
@Slf4j
public class VersionLockAOPAspect {
/**
* 之前
* @param joinPoint
*/
@Before(value = "@annotation(com.gscloud.modules.pos.upgrade.aop.VersionLockAOP)")
public void VersionLockAOPBeforePoint(JoinPoint joinPoint) {
try {
switch (joinPoint.getSignature().getName()) {
case "saveVersion":
if (!SingleUtil.SINGLE.getReentrantLockSaveVersion().tryLock(2000L, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("saveVersion获取锁失败");
}
return;
case "saveVersionHistory":
if (!SingleUtil.SINGLE.getReentrantLockSaveUpgrade().tryLock(2000L, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("saveVersionHistory获取锁失败");
}
return;
}
} catch (InterruptedException e) {
throw new RuntimeException("获取锁:" + e.getMessage());
}
}
/**
* 之后
* @param joinPoint
*/
@After(value = "@annotation(com.gscloud.modules.pos.upgrade.aop.VersionLockAOP)")
public void VersionLockAOPAfterPoint(JoinPoint joinPoint) {
switch (joinPoint.getSignature().getName()) {
case "saveVersion":
if (SingleUtil.SINGLE.getReentrantLockSaveVersion().isLocked()) {
SingleUtil.SINGLE.getReentrantLockSaveVersion().unlock();
}
return;
case "saveVersionHistory":
if(SingleUtil.SINGLE.getReentrantLockSaveUpgrade().isLocked()){
SingleUtil.SINGLE.getReentrantLockSaveUpgrade().unlock();
}
return;
}
}
}
3、在对应的方法上使用
执行该方法前后都会进入切点方法执行对应逻辑