All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.doudou.common.aop.lock.redis.RLockAop Maven / Gradle / Ivy

package top.doudou.common.aop.lock.redis;

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.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;
import top.doudou.common.redis.annotation.CLock;
import top.doudou.common.redis.lock.LockUtils;
import top.doudou.common.redis.mode.LockMode;
import top.doudou.core.util.ElExpression;

import java.lang.reflect.Method;

/**
 * order设置优先级 越小优先级越高 为了在事务提交之后 再释放分布式锁
 */
@Aspect
@Order(1)
public class RLockAop {

    /**
     * 分布式锁Aop
     * @return
     */
    @Around("@annotation(top.doudou.common.redis.annotation.CLock)")
    public Object rLockAop(ProceedingJoinPoint joinPoint) throws Throwable {

        //获得方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CLock cLock = method.getAnnotation(CLock.class);

        //解析分布式锁的key值
        String key = ElExpression.parseExpression(cLock.key(),method, joinPoint.getArgs(),String.class, null);

        //分布式锁对象
        try {
            //判断是否为自动加锁模式
            if (cLock.lockMode() == LockMode.AUTO && !StringUtils.isEmpty(key)) {
                //设置分布式锁
                LockUtils.lockSync(key);
            }

            Object result = joinPoint.proceed();
            return result;
        } catch (Throwable e) {
            throw e;
        } finally {
            //解除分布式锁
            LockUtils.unlock();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy