Commit fece0554 by ThomasAdv

oneId获取redis分布式锁

1 parent e56a7e7c
...@@ -69,6 +69,14 @@ ...@@ -69,6 +69,14 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId> <artifactId>spring-boot-starter-amqp</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-redis</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package cn.com.glsx.cdp.common.distributeLock;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.integration.support.locks.LockRegistry;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
@Slf4j
public class DistributeLockMethodInterceptor implements MethodInterceptor {
private LockRegistry lockRegistry;
private Integer globalLockSecondsTime;
public DistributeLockMethodInterceptor(LockRegistry lockRegistry, Integer globalLockSecondsTime) {
this.lockRegistry = lockRegistry;
this.globalLockSecondsTime = globalLockSecondsTime;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
String className = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
GlsxDistributeLockable axLockable = invocation.getThis().getClass().getMethod(invocation.getMethod().getName(), invocation.getMethod().getParameterTypes()).getAnnotation(GlsxDistributeLockable.class);
if (StringUtils.isBlank(axLockable.name())) {
throw new RuntimeException(MessageFormat.format("{0}.{1} @GlsxDistributeLockable name not has config", className, methodName));
} else {
int time = axLockable.time();
TimeUnit timeUnit = axLockable.timeUnit();
if (time < 0 && this.globalLockSecondsTime != null && this.globalLockSecondsTime > 0) {
time = this.globalLockSecondsTime;
timeUnit = TimeUnit.SECONDS;
}
if (time <= 0) {
Object result = invocation.proceed();
return result;
} else {
String threadName = Thread.currentThread().getName();
String lockName = this.parseKey(axLockable.name(), invocation.getMethod(), invocation.getArguments());
Lock lock = this.lockRegistry.obtain(lockName);
log.info("{}.{},lockName:{},threadName:{}, time:{},timeUnit:{} try to Lock.", new Object[]{className, methodName, lockName, threadName, time, timeUnit});
boolean isLock = lock.tryLock((long)time, timeUnit);
log.info("{}.{},lockName:{},threadName:{},time:{},timeUnit:{} try to Lock result:{}", new Object[]{className, methodName, lockName, threadName, time, timeUnit, isLock});
if (!isLock) {
Throwable throwable = (Throwable)axLockable.timeoutException().newInstance();
Field detailMessage = FieldUtils.getField(throwable.getClass(), "detailMessage", true);
detailMessage.set(throwable, MessageFormat.format("{0}.{1},lockName:{2},threadName:{3} get lock timeout in {4} {5}.", className, methodName, lockName, threadName, time, timeUnit.name()));
throw throwable;
} else {
Object var11;
try {
var11 = invocation.proceed();
} finally {
lock.unlock();
log.info("{}.{},lockName:{},threadName:{},time:{},timeUnit:{} unlock", new Object[]{className, methodName, lockName, threadName, time, timeUnit});
}
return var11;
}
}
}
}
private String parseKey(String key, Method method, Object[] args) {
if (StringUtils.isEmpty(key)) {
return null;
} else if (key.indexOf("#") == -1) {
return key;
} else {
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paraNameArr = u.getParameterNames(method);
if (paraNameArr != null && paraNameArr.length != 0) {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
for(int i = 0; i < paraNameArr.length; ++i) {
context.setVariable(paraNameArr[i], args[i]);
}
Expression e = parser.parseExpression(key);
return (String)e.getValue(context, String.class);
} else {
return key;
}
}
}
}
package cn.com.glsx.cdp.common.distributeLock;
public class GetLockTimeoutException extends Exception {
private static final long serialVersionUID = -1227993606335097450L;
public GetLockTimeoutException() {
}
public GetLockTimeoutException(String message) {
super(message);
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.cdp.common.distributeLock;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GlsxDistributeLockable {
String name() default "";
int time() default -1;
TimeUnit timeUnit() default TimeUnit.SECONDS;
Class<? extends Throwable> timeoutException() default GetLockTimeoutException.class;
}
package cn.com.glsx.cdp.config;
import cn.com.glsx.cdp.common.distributeLock.DistributeLockMethodInterceptor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.integration.redis.util.RedisLockRegistry;
@Configuration
public class InteceptorConfig {
@Bean
public DefaultPointcutAdvisor glsxDistributeLockAdvisor(RedisConnectionFactory redisConnectionFactory){
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
RedisLockRegistry lockRegistry = new RedisLockRegistry(redisConnectionFactory, "lock");
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("@annotation(cn.com.glsx.cdp.common.distributeLock.GlsxDistributeLockable)");
advisor.setPointcut(pointcut);
advisor.setAdvice(new DistributeLockMethodInterceptor(lockRegistry, 10));
return advisor;
}
}
...@@ -2,6 +2,7 @@ package cn.com.glsx.cdp.modules.service; ...@@ -2,6 +2,7 @@ package cn.com.glsx.cdp.modules.service;
import cn.com.glsx.cdp.common.constant.Constants; import cn.com.glsx.cdp.common.constant.Constants;
import cn.com.glsx.cdp.common.constant.OneIdConfigConstatns; import cn.com.glsx.cdp.common.constant.OneIdConfigConstatns;
import cn.com.glsx.cdp.common.distributeLock.GlsxDistributeLockable;
import cn.com.glsx.cdp.modules.model.FindOrCreateOneIdParam; import cn.com.glsx.cdp.modules.model.FindOrCreateOneIdParam;
import cn.com.glsx.cdp.modules.model.OneIdFieldConfigDTO; import cn.com.glsx.cdp.modules.model.OneIdFieldConfigDTO;
import cn.com.glsx.cdp.modules.model.OneIdMappingDTO; import cn.com.glsx.cdp.modules.model.OneIdMappingDTO;
...@@ -47,7 +48,6 @@ public class OneIdService { ...@@ -47,7 +48,6 @@ public class OneIdService {
* @author caiym * @author caiym
* @date 2023年09月21日 16:07:51 * @date 2023年09月21日 16:07:51
*/ */
@Transactional(propagation= Propagation.REQUIRED,rollbackFor=RpcServiceException.class)
public String findOrCreateOneId(FindOrCreateOneIdParam param){ public String findOrCreateOneId(FindOrCreateOneIdParam param){
log.info("findOrCreateOneId, param:{}", param); log.info("findOrCreateOneId, param:{}", param);
RpcAssert.assertNotNull(param, DefaultErrorEnum.DATA_NULL,"param not be null"); RpcAssert.assertNotNull(param, DefaultErrorEnum.DATA_NULL,"param not be null");
...@@ -74,23 +74,23 @@ public class OneIdService { ...@@ -74,23 +74,23 @@ public class OneIdService {
* 查找或创建oneId * 查找或创建oneId
* *
* @param finalOneId * @param finalOneId
* @param readyMatchOneIdFieldConfig * @param oneIdFieldConfig
* @return java.lang.String * @return java.lang.String
* @author caiym * @author caiym
* @date 2023年09月21日 16:53:44 * @date 2023年09月21日 16:53:44
*/ */
@Transactional(propagation= Propagation.REQUIRED,rollbackFor=RpcServiceException.class) @GlsxDistributeLockable(name = "'OneIdService_findOrCreateOneId_' + #oneIdFieldConfig.oneIdBelongOrgId + '_' + #oneIdFieldConfig.businessType + '_' + #oneIdFieldConfig.fieldName + '_' + #oneIdFieldConfig.fieldValue", time = 10, timeoutException = RpcServiceException.class)
public String findOrCreateOneId(String finalOneId, OneIdFieldConfigDTO readyMatchOneIdFieldConfig){ public String findOrCreateOneId(String finalOneId, OneIdFieldConfigDTO oneIdFieldConfig){
log.info("findOrCreateOneId,finalOneId:{},fieldName:{}", readyMatchOneIdFieldConfig.getFieldName()); log.info("findOrCreateOneId,finalOneId:{},fieldName:{}", oneIdFieldConfig.getFieldName());
OneIdMappingDTO oneIdMapping = oneIdMappingService.getOneIdMapping(readyMatchOneIdFieldConfig.getOneIdBelongOrgId(), OneIdMappingDTO oneIdMapping = oneIdMappingService.getOneIdMapping(oneIdFieldConfig.getOneIdBelongOrgId(),
readyMatchOneIdFieldConfig.getBusinessType(), readyMatchOneIdFieldConfig.getFieldName(), oneIdFieldConfig.getBusinessType(), oneIdFieldConfig.getFieldName(),
readyMatchOneIdFieldConfig.getFieldValue()); oneIdFieldConfig.getFieldValue());
if (oneIdMapping == null) { if (oneIdMapping == null) {
if (StringUtils.isBlank(finalOneId)) { if (StringUtils.isBlank(finalOneId)) {
log.info("generate new oneId,fieldName:{}", readyMatchOneIdFieldConfig.getFieldName()); log.info("generate new oneId,fieldName:{}", oneIdFieldConfig.getFieldName());
finalOneId = gainIdService.globalUniqueId(Constants.ONEID_PREFIX); finalOneId = gainIdService.globalUniqueId(Constants.ONEID_PREFIX);
} }
oneIdMappingService.saveOneIdMapping(finalOneId, readyMatchOneIdFieldConfig); oneIdMappingService.saveOneIdMapping(finalOneId, oneIdFieldConfig);
}else if (StringUtils.isBlank(finalOneId)) { }else if (StringUtils.isBlank(finalOneId)) {
finalOneId = oneIdMapping.getOneId(); finalOneId = oneIdMapping.getOneId();
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!