1、自定义注解
package com.example.demo.annotation;
import java.lang.annotation.*;
/**
* desc: 自定义 redisson 分布式锁注解
*
* @author: 邢阳
* @mail: xydeveloper@126.com
* @create 2021-05-28 16:50
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Lock {
/**
* 锁的key spel 表达式
*
* @return
*/
String key();
/**
* 持锁时间
*
* @return
*/
long keepMills() default 20;
/**
* 没有获取到锁时,等待时间
*
* @return
*/
long maxSleepMills() default 30;
}
2、aop解析注解
package com.example.demo.utils;
import com.example.demo.annotation.Lock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
public class LockAspect {
@Autowired
private RedissonClient redissonClient;
private final SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
private final DefaultParameterNameDiscoverer defaultParameterNameDiscoverer = new DefaultParameterNameDiscoverer();
@Around("@annotation(com.example.demo.annotation.Lock)")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object object = null;
RLock lock = null;
try {
Lock lockEntity = (((MethodSignature) proceedingJoinPoint.getSignature()).getMethod())
.getAnnotation(Lock.class);
lock = redissonClient.getLock(getKeyBySpeL(lockEntity.key(), proceedingJoinPoint));
if (Objects.nonNull(lock)) {
if (lock.tryLock(lockEntity.maxSleepMills(), lockEntity.keepMills(), TimeUnit.SECONDS)) {
object = proceedingJoinPoint.proceed();
} else {
throw new RuntimeException();
}
}
} finally {
if (Objects.nonNull(lock) && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
return object;
}
public String getKeyBySpeL(String spel, ProceedingJoinPoint proceedingJoinPoint) {
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
String[] paramNames = defaultParameterNameDiscoverer.getParameterNames(methodSignature.getMethod());
EvaluationContext context = new StandardEvaluationContext();
Object[] args = proceedingJoinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
context.setVariable(paramNames[i], args[i]);
}
return String.valueOf(spelExpressionParser.parseExpression(spel).getValue(context));
}
}
3、service中使用注解加锁使用
@Service
public class LockService {
@Lock(key = "#user.id", keepMills = 10, maxSleepMills = 15)
public String lock(User user) {
System.out.println("持锁");
return "";
}
}