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

com.sghd.common.utils.lock.service.LockInAspect Maven / Gradle / Ivy

The newest version!
package com.sghd.common.utils.lock.service;
 
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.sghd.common.utils.lock.anno.LockIn;
import com.sghd.common.utils.lock.anno.LockType;

@Aspect
@Component
public class LockInAspect {
	private static final Logger logger = LoggerFactory.getLogger(LockInAspect.class);

	/** 锁方法拦截处理 */
	@Around("@annotation(lockIn)")
	public Object execute(ProceedingJoinPoint pjp, LockIn lockIn) throws Throwable {
		Signature sign = pjp.getSignature();
		if (!(sign instanceof MethodSignature)) {
			logger.error("不支持的拦截切面:{}", sign);
			return pjp.proceed(pjp.getArgs());
		}
		String registerName = getRegsiterName(pjp.getTarget().getClass(), lockIn);

		ReentrantReadWriteLock rwLock = _cache.get(registerName);
		if(rwLock == null){
			rwLock = new ReentrantReadWriteLock();
			 _cache.putIfAbsent(registerName, rwLock);
			 rwLock = _cache.get(registerName);
		}

		Lock lock = null;
		LockType lockType = lockIn.lockType();
		if (lockType.equals(LockType.READ)) {
			lock = rwLock.readLock();
		} else {
			lock = rwLock.writeLock();
		}

		if(logger.isDebugEnabled()){
			logger.debug("锁类型:" + lockType + ",上锁 : " + registerName + ",时间:" + System.currentTimeMillis());
		}
		lock.lock();
		try {
			return pjp.proceed(pjp.getArgs());
		} finally {
			lock.unlock();
			if(logger.isDebugEnabled()){
				logger.debug("锁类型:" + lockType + ",解锁 : " + registerName + ",时间:" + System.currentTimeMillis());
			}
		}
	}

	private ConcurrentHashMap _cache = new ConcurrentHashMap<>();

	private String getRegsiterName(Class clazz, LockIn annotation) {
		String registerName = annotation.registerName();
		if (registerName.isEmpty()) {
			registerName = clazz.getSimpleName();
		} else {
			registerName = clazz.getSimpleName() + "_" + registerName;
		}
		return registerName;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy