设置每5秒内的第一个不同数据请求进入
pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency>
@Aspect
@Configuration
@Slf4j
public class LockMethodAspect {
//设置每5秒中的第一个不同数据的请求可以进入
private static final Cache<String, Object> CACHE = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(5, TimeUnit.SECONDS).build();
@SneakyThrows
@Around("execution(public * *(..)) && @annotation(cn.com.dxy.annotation.LocalLock)")
public Object interceptor(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LocalLock localLock = method.getAnnotation(LocalLock.class);
String key = getKey(localLock.key(), joinPoint.getArgs());
if (!StringUtils.isEmpty(key)) {
if (CACHE.getIfPresent(key) != null) {
throw new ServiceException("请勿重复请求!");
}
CACHE.put(key, key);
}
return joinPoint.proceed();
}
private String getKey(String keyExpress, Object[] args) {
for (int i = 0; i < args.length; i++) {
keyExpress = keyExpress.replace("arg[" + i + "]", args[i].toString());
}
return keyExpress;
}
}
使用: