Commit b137b20d by zhouhaibao

[+]分布式锁添加

1 parent 76e06c97
...@@ -91,6 +91,11 @@ ...@@ -91,6 +91,11 @@
<artifactId>freemarker</artifactId> <artifactId>freemarker</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-redis</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -18,6 +18,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients; ...@@ -18,6 +18,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
import com.glsx.plat.context.EnableRestAdmin; import com.glsx.plat.context.EnableRestAdmin;
import cn.com.glsx.process.job.DynamicTaskService; import cn.com.glsx.process.job.DynamicTaskService;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/** /**
* @author payu * @author payu
...@@ -27,6 +28,7 @@ import cn.com.glsx.process.job.DynamicTaskService; ...@@ -27,6 +28,7 @@ import cn.com.glsx.process.job.DynamicTaskService;
@EnableDiscoveryClient @EnableDiscoveryClient
@EnableFeignClients(basePackages = {"cn.com.glsx.*.api"}) @EnableFeignClients(basePackages = {"cn.com.glsx.*.api"})
@SpringBootApplication @SpringBootApplication
@EnableAspectJAutoProxy
public class Application implements CommandLineRunner { public class Application implements CommandLineRunner {
@Autowired @Autowired
......
package cn.com.glsx.process.modules.service; package cn.com.glsx.process.modules.service;
import java.util.ArrayList; import cn.com.glsx.process.modules.converter.UserConverter;
import java.util.Date; import cn.com.glsx.process.modules.entity.User;
import java.util.List; import cn.com.glsx.process.modules.mapper.UserMapper;
import java.util.Map; import cn.com.glsx.process.modules.model.UserDTO;
import cn.com.glsx.process.modules.model.UserSearch;
import javax.annotation.Resource; import cn.com.glsx.process.redis.DistributedLock;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.glsx.plat.common.utils.ObjectUtils; import com.glsx.plat.common.utils.ObjectUtils;
import com.glsx.plat.common.utils.SessionUtils; import com.glsx.plat.common.utils.SessionUtils;
...@@ -21,12 +14,17 @@ import com.glsx.plat.exception.ResultException; ...@@ -21,12 +14,17 @@ import com.glsx.plat.exception.ResultException;
import com.glsx.plat.exception.SystemMessage; import com.glsx.plat.exception.SystemMessage;
import com.glsx.plat.jwt.base.ComJwtUser; import com.glsx.plat.jwt.base.ComJwtUser;
import com.glsx.plat.jwt.util.JwtUtils; import com.glsx.plat.jwt.util.JwtUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import cn.com.glsx.process.modules.converter.UserConverter; import javax.annotation.Resource;
import cn.com.glsx.process.modules.entity.User; import java.util.ArrayList;
import cn.com.glsx.process.modules.mapper.UserMapper; import java.util.Date;
import cn.com.glsx.process.modules.model.UserDTO; import java.util.List;
import cn.com.glsx.process.modules.model.UserSearch; import java.util.Map;
/** /**
* @author liuyf * @author liuyf
...@@ -133,4 +131,9 @@ public class UserDemoService { ...@@ -133,4 +131,9 @@ public class UserDemoService {
return user; return user;
} }
@DistributedLock(key = "'UserDemoService_' + #user.account", expireTime = 1)
public void testRedis(User user) {
System.out.println("user");
}
} }
package cn.com.glsx.process.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.PostConstruct;
@Configuration
public class AopConfig {
@Value("@annotation(cn.com.glsx.process.redis.DistributedLock)")
private String point;
@Bean
@AutoConfigureOrder(value = 2)
public AspectJExpressionPointcutAdvisor aspectJExpressionPointcutAdvisor(){
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.setAdvice(new DistributedLockInterceptor());
advisor.setExpression(point);
return advisor;
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.process.redis;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributedLock {
/**
* 分布式锁key
*/
String key() default "";
/**
* 过期时间
*
* @return
*/
long expireTime() default 30000;
}
package cn.com.glsx.process.redis;
import cn.com.glsx.process.modules.service.SopService;
import com.glsx.plat.context.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.data.redis.core.RedisTemplate;
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.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class DistributedLockInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
DistributedLock distributedLock = method.getAnnotation(DistributedLock.class);
if (distributedLock != null) {
String lockKey = distributedLock.key();
long expireTime = distributedLock.expireTime();
boolean locked = false;
try {
String lockName = parseKey(distributedLock.key(), invocation.getMethod(), invocation.getArguments());
log.info("拦截key{}",lockName);
locked = tryLock(lockKey, expireTime);
if (locked) {
return invocation.proceed();
} else {
throw new IllegalStateException("Failed to acquire distributed lock");
}
} finally {
if (locked) {
unlock(lockKey);
}
}
} else {
return invocation.proceed();
}
}
private boolean tryLock(String lockKey, long expireTime) {
// 使用Redis的SETNX命令来尝试获取锁
RedisTemplate restRedisTemplate = SpringUtils.getBean("restRedisTemplate");
Boolean result = restRedisTemplate.opsForValue().setIfAbsent(lockKey, "locked", expireTime, TimeUnit.MILLISECONDS);
return result != null && result;
}
private void unlock(String lockKey) {
RedisTemplate restRedisTemplate = SpringUtils.getBean("restRedisTemplate");
restRedisTemplate.delete(lockKey);
}
private String parseKey(String key, Method method, Object[] args) {
if (StringUtils.isEmpty(key)) {
return null;
}
if (key.indexOf("#") == -1) {
return key;
}
//获取被拦截方法参数名列表(使用Spring支持类库)
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paraNameArr = u.getParameterNames(method);
if (paraNameArr == null || paraNameArr.length == 0) {
return key;
}
//使用SPEL进行key的解析
ExpressionParser parser = new SpelExpressionParser();
//SPEL上下文
StandardEvaluationContext context = new StandardEvaluationContext();
//把方法参数放入SPEL上下文中
for (int i = 0; i < paraNameArr.length; i++) {
context.setVariable(paraNameArr[i], args[i]);
}
Expression e = parser.parseExpression(key);
return e.getValue(context, String.class);
}
}
\ No newline at end of file \ No newline at end of file
...@@ -2,6 +2,7 @@ package cn.com.glsx.cn.com.glsx; ...@@ -2,6 +2,7 @@ package cn.com.glsx.cn.com.glsx;
import cn.com.glsx.Application; import cn.com.glsx.Application;
import cn.com.glsx.process.modules.entity.SopDataSource; import cn.com.glsx.process.modules.entity.SopDataSource;
import cn.com.glsx.process.modules.entity.User;
import cn.com.glsx.process.modules.service.SopDataSourceService; import cn.com.glsx.process.modules.service.SopDataSourceService;
import cn.com.glsx.process.modules.service.UserDemoService; import cn.com.glsx.process.modules.service.UserDemoService;
import cn.com.glsx.process.plugin.dbconn.FlowDataAdapterImpl; import cn.com.glsx.process.plugin.dbconn.FlowDataAdapterImpl;
...@@ -15,9 +16,13 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -15,9 +16,13 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.math.BigDecimal;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** /**
* 测试spring cloud 服务调用方式 * 测试spring cloud 服务调用方式
...@@ -66,4 +71,56 @@ public class TestApplication { ...@@ -66,4 +71,56 @@ public class TestApplication {
System.out.println(JSON.toJSONString(instance)); System.out.println(JSON.toJSONString(instance));
} }
@Test
public void testredis() throws InterruptedException {
//设置并发数量
int count = 10;
//线程池准备
CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
ExecutorService executorService = Executors.newFixedThreadPool(count);
//开始时间
long now = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
executorService.execute(new Task(cyclicBarrier, i, userDemoService));
}
executorService.shutdown();
while (!executorService.isTerminated()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Task implements Runnable {
private CyclicBarrier cyclicBarrier;
private int count;
private UserDemoService userDemoService;
public Task(CyclicBarrier cyclicBarrier, int count, UserDemoService userDemoService) {
this.cyclicBarrier = cyclicBarrier;
this.count = count;
this.userDemoService = userDemoService;
}
@Override
public void run() {
try {
cyclicBarrier.await();
User user=new User();
user.setAccount("123456");
userDemoService.testRedis(user);
} catch (Exception e) {
System.out.println("出现超时的线程" + count);
e.printStackTrace();
}
}
}
} }
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!