com.lx.boot.lock.LockManager Maven / Gradle / Ivy
package com.lx.boot.lock;
import com.lx.annotation.Note;
import com.lx.entity.NoArgsFunc;
import com.lx.util.LX;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.core.StringRedisTemplate;
@Aspect
@Configuration
@EnableAspectJAutoProxy
public class LockManager {
private static Logger logger = LoggerFactory.getLogger(LockManager.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Note("获取锁 lockKey 锁的值, lockTime 锁失效时间")
public RedisLock getLock(String lockKey, int lockTime){
return new RedisLock(stringRedisTemplate, "lock:" +lockKey, lockTime);
}
@Note("尝试获取锁,并执行代码! lockKey 锁的值, lockTime 锁失效时间, timeOut 等待时间 , func 获取锁后执行函数")
public void tryLock(String lockKey, int lockTime, long timeOut, NoArgsFunc func){
RedisLock lock = new RedisLock(stringRedisTemplate, "lock:" + lockKey, lockTime);
if (lock.tryLock(timeOut)) {
try {
func.exec();
}finally {
if (!lock.unlock()) {
logger.warn("释放分布式锁失败, key=" + "lock:" + lockKey);
}
}
}
LX.exMsg("操作过快,请稍后重试!");
}
@Around(value = "@annotation(lock)", argNames = "pjp, lock")
public Object around(ProceedingJoinPoint pjp, Lock lock) throws Throwable {
Class clazz = pjp.getTarget().getClass();
String methodName = pjp.getSignature().getName();
String key = lock.key();
if (LX.isEmpty(key)) {
key = "lock:" + clazz.getName()+ ":" + methodName;
}else{
key = "lock:" +SpelParserUtils.parse(key, pjp);
}
RedisLock redisLock = new RedisLock(stringRedisTemplate, key, lock.lockTime());
Object result = null;
// 获得锁
if (redisLock.tryLock(lock.timetOut())) {
try {
result = pjp.proceed();
}finally {
if (!redisLock.unlock()) {
logger.warn("释放分布式锁失败, key=" + key);
}
}
}else {
logger.error("获取分布式锁失败, key=" + key);
LX.exMsg(lock.errorMessage());
}
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy