通过自定义注解+切面给执行方法加锁

通过自定义注解+切面给执行方法加锁

上代码
一、自定义注解类=================================
@Target({ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface XXXLock {
String lockKey();
String keyExtendField() default StringUtils.EMPTY;
String lockDesc() default “aaaa”;
long expireTime() default 1111111L;
}

二、类中加了注解的方法========================
@Service
public class XXXServiceImpl{
private String bbbbype;
@XXXLock (lockKey = xxxKey, keyExtendField = “bbbbype”)
public void acquireMorningStaticContractInfo() {}
}

三、切面类===============================
@Component
@Aspect
public class XXXLockAspect {
@Pointcut(“@annotation(annotation.XXXLock )”)
public void pointCut() {}
@Around(“pointCut()”)
public Object doAround(ProceedingJoinPoint joinPoint) throws Exception {
Object result = null;
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
//获取目标对象
Object target = joinPoint.getTarget();
//目标方法
Method method = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
//方法注解
XXXLock annotation = method.getAnnotation(XXXLock.class);
//注解定义的key
String key = annotation.lockKey();
if (!StringUtils.EMPTY.equals(annotation.keyExtendField())) {
//通过反射获取扩展字段
Field bbbbypeF = target.getClass().getDeclaredField(annotation.keyExtendField());
ctyTypeF.setAccessible(true);
//获取字段值
String keyExtend = (String) bbbbypeF.get(target);
//拼接生成key
key = key + xxxx + keyExtend;
}
XXXLockDO xxxLockDO = DomainFactory.create(XXXLockDO.class);
//是否获取到锁
boolean isAcquired = xxxLockDO .setLockKey(key)
.setLockDesc(annotation.lockDesc())
.setLockExpireTime(annotation.expireTime())
.acquireLock();
if (isAcquired) {
try {
//获取到锁,执行方法,否则不执行
result = joinPoint.proceed();
} catch (Throwable throwable) {
throw new Exception(xxxx);
}
} else {
}
return result;
}
}

四、获取锁的类的方法=========================
public class XXXLockDO {
@Override
public boolean acquireLock() {
Date now = new Date();
this.setCreateTime(now);
this.setLastUpdateTime(now);
try {
//通过key去库中查询是否存在锁
XXXLockPO lockInstance = repository.getKey(this.lockKey);
if (Objects.nonNull(lockInstance)) {//如果当前key存在锁
if (lockInstance.getCreateTime().getTime() + Optional.ofNullable(lockInstance.getLockExpireTime()).orElse(0L) < now.getTime()) {//判断锁是否过期
//如果锁过期就释放锁,删除表中记录
repository.releaseLock(lockInstance.getLockId());
} else {
//没有获取到锁
return false;
}
}
//表中不存在记录就入库加锁,返回true,获取到锁
repository.insert(convertor.convert(this));
} catch (Exception e) {
return false;
}
return true;
}
}

你可能感兴趣的:(java,开发语言)