1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import cn.com.yeexun.common.redis.annotation.RedissionLock; import cn.com.yeexun.common.redis.utils.SpElUtils; import cn.com.yeexun.core.exception.BizException; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;
import javax.annotation.Resource; import java.lang.reflect.Method; @Aspect @Component public class RedissionAspect { private static final Logger logger = LoggerFactory.getLogger(RedissionAspect.class);
@Resource private RedissonClient redissonClient;
@Around("@annotation(redissionLock)") public Object lock(ProceedingJoinPoint proceedingJoinPoint, RedissionLock redissionLock) {
Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod(); String key = SpElUtils.parseSpEl(method, proceedingJoinPoint.getArgs(), redissionLock.keyPrefix());
String lockKey = String.format("lock:%s:%s", key, redissionLock.type()); RLock lock = redissonClient.getLock(lockKey); boolean hasLock = false; try { hasLock = lock.tryLock(redissionLock.waitTime(), redissionLock.expire(), redissionLock.timeUnit()); if (hasLock) { return proceedingJoinPoint.proceed(); } } catch (Throwable throwable) { logger.error(throwable.getMessage()); throw new BizException(throwable.getMessage()); } finally { if (hasLock) { lock.unlock(); } } throw new BizException("获取分布式锁失败"); } }
|