package com.kjhy.common.core.aop;
import com.kjhy.common.core.config.RedissonConfig;
import com.kjhy.common.core.exception.Exceptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
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.redisson.api.RLock;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
/**
* @author WenYF
* @email [email protected]
* @since 2021/4/6
*/
@Aspect
@Component
@Slf4j
@Order(0)
public class DistributeLockAop {
@Pointcut("@annotation(com.kjhy.common.core.aop.DistributeLock)")
public void distributeLock() {
}
/**
* 对方法拦截后进行上锁
*
* @param pjp
* @return
* @throws Throwable
*/
@Around("distributeLock()")
public Object distributeLock(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature msig = (MethodSignature) pjp.getSignature();
String classname = pjp.getTarget().getClass().getName();
Method currentMethod = msig.getMethod();
DistributeLock annotation = currentMethod.getAnnotation(DistributeLock.class);
// class全路径-方法 作为key
StringJoiner joiner = new StringJoiner("-");
joiner.add(classname);
joiner.add(currentMethod.getName());
// 函数参数 作为key
int[] params = annotation.keyWithParams();
if (params.length == 0) {
Object[] args = pjp.getArgs();
for (Object object : args) {
if (object != null) {
joiner.add(object.getClass().getName());
joiner.add(object.toString());
} else {
joiner.add(null);
}
}
}
else {
Object[] args = pjp.getArgs();
for (int paramsIndex : params) {
if (paramsIndex == 0) {
continue;
}
Object object = args[paramsIndex - 1];
if (object != null) {
joiner.add(object.getClass().getName());
joiner.add(object.toString());
} else {
joiner.add(null);
}
}
}
// 锁参数
long waitTime = annotation.waitTime();
long leaseTime = annotation.leaseTime();
TimeUnit timeUnit = annotation.timeUnit();
if (waitTime < 0) {
waitTime = 0;
}
if (leaseTime < 0) {
leaseTime = 0;
}
String str = joiner.toString();
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] bs = digest.digest(str.getBytes());
String key = "distribute.lock." + MD5Encoder.encode(bs);
log.warn("distributeLock str={}, waitTime={}, leaseTime={}, timeUnit={}, key={}"
, str, waitTime, leaseTime, timeUnit, key);
RLock lock = RedissonConfig.getRedisson().getLock(key);
// 判断锁是否存在
if (lock.isLocked()) {
log.warn("distributeLock exist lock, key={}", key);
String message = annotation.lockExist();
if (StringUtils.isBlank(message)) {
message = "请勿重复操作";
}
Exceptions.throwException(message);
}
boolean lockRet = false;
try {
// 上锁
lockRet = lock.tryLock(waitTime, leaseTime, timeUnit);
if (!lockRet) {
// 上锁失败
log.warn("distributeLock lock bad, key={}", key);
String message = annotation.lockBad();
if (StringUtils.isBlank(message)) {
message = "请勿重复操作";
}
Exceptions.throwException(message);
}
log.warn("distributeLock lock success, key={}", key);
return pjp.proceed();
} finally {
if (lockRet) {
try {
lock.unlock();
} catch (Exception e) {
log.warn(e.getLocalizedMessage() + ", [" + str + "]"
+ " method takes too long time, please optimize code.", e);
}
log.warn("distributeLock unlock, key={}", key);
}
}
}
}
package com.kjhy.common.core.aop;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
import static java.lang.annotation.ElementType.METHOD;
/**
* 分布式锁,在controller/service层方法使用此注解,将会自动上分布式锁,默认key=类名全路径+方法+参数,
* 忽略参数部分{@link #keyWithParams()}
* 事务在此之后切入
*
* @author WenYF
* @email [email protected]
* @since 2021/4/6
*/
@Target({METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DistributeLock {
/**
* 当锁已经存在时候,抛出的异常信息
*
* @return
*/
String lockExist() default "";
/**
* 上锁失败信息
*
* @return
*/
String lockBad() default "";
/**
* 等待获取锁时间,必须>=0
*
* @return 默认10
*/
long waitTime() default 10;
/**
* 获得锁最长时间,到时间后自动释放,必须大于>=0
*
* @return 默认10
*/
long leaseTime() default 10;
/**
* 时间单位
*
* @return 默认TimeUnit.SECONDS
*/
TimeUnit timeUnit() default TimeUnit.SECONDS;
/**
* 组成分布式锁key,{}默认使用方法名+所有参数组成,{1,....}表示方法名+第1-n个参数,从1开始
* {0}表示仅使用方法名
*
* @return {}
*/
int[] keyWithParams() default {};
}
// 0使用方法名+1使用第一个参数组合成key
@DistributeLock(keyWithParams = {0, 1})
@Override
public PeriodAdjustResultVO startAdjustPaymentApproval(String paymentId, PeriodAdjustDTO dto) {
xxx
}
[12-30 09:35:19]-[TID:N/A] [http-nio-9045-exec-8] WARN c.k.c.core.aop.DistributeLockAop -distributeLock str=com.kjhy.settlement.service.impl.PeriodAdjustServiceImpl-adjustPayment-java.lang.String-1455087246047268866, waitTime=10, leaseTime=10, timeUnit=SECONDS, key=distribute.lock.a11ad190e16766e12cc05b4b28e5d2a9
[12-30 09:35:19]-[TID:N/A] [http-nio-9045-exec-8] WARN c.k.c.core.aop.DistributeLockAop -distributeLock lock success, key=distribute.lock.a11ad190e16766e12cc05b4b28e5d2a9
xxx
[12-30 09:35:19]-[TID:N/A] [http-nio-9045-exec-8] WARN c.k.c.core.aop.DistributeLockAop -distributeLock unlock, key=distribute.lock.a11ad190e16766e12cc05b4b28e5d2a9