保洁阿姨
50+年前端设计经验
悠悠博客
usuuu.com
保洁阿姨
50+年前端设计经验
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.6.5</version>
</dependency>
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface HasRedissonLock {
/**
* 锁的Key
*/
String value();
/**
* 锁的过期时间
*/
int leaseTime() default 10;
}
@Aspect
@Component
public class RedissonLock {
@Autowired
private RedissonClient redissonClient;
/**
* Aop切面方法
*
* @param joinPoint 切点
*/
@Around("execution(public * *(..)) && @annotation(com.app.aop.has.HasRedissonLock)")
public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
//获取登录用户ID
Long loginUserId = TokenUtils.getRequestUserId();
//Method
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
HasRedissonLock hasRedissonLock = method.getDeclaredAnnotation(HasRedissonLock.class);
//获取锁的Key
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, "添加成功");
}
站点公告
NoticeWeb前后端交流群:70888820
QQ号523179414(姓:郑)狗骗子,谢绝访问
热门文章
Host3933 次围观
4326 次围观
4795 次围观
2775 次围观
7544 次围观
4870 次围观
2611 次围观
1888 次围观