pom.xml
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.6.5</version>
</dependency>
HasRedissonLock.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface HasRedissonLock {
String value();
int leaseTime() default 10;
}
RedissonLock.java
@Aspect
@Component
public class RedissonLock {
@Autowired
private RedissonClient redissonClient;
@Around("execution(public * *(..)) && @annotation(com.app.aop.has.HasRedissonLock)")
public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
Long loginUserId = TokenUtils.getRequestUserId();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
HasRedissonLock hasRedissonLock = method.getDeclaredAnnotation(HasRedissonLock.class);
String lockKey = hasRedissonLock.value() + ":" + loginUserId;
long leaseTime = hasRedissonLock.leaseTime();
RLock lock = redissonClient.getLock(lockKey);
boolean isLocked = false;
try {
isLocked = lock.tryLock(leaseTime, TimeUnit.SECONDS);
if (!isLocked) throw new BusinessException("请勿重复请求");
return joinPoint.proceed();
} finally {
if (isLocked) lock.unlock();
}
}
}
接口使用
@HasRedissonLock("save_article")
@PostMapping("/save")
public R<?> save(@RequestBody ArticleBo bo) {
articleService.save(bo);
return R.ok(null, "添加成功");
}