Java注解如何基于Redission实现分布式锁
这篇文章主要介绍了Java注解如何基于Redission实现分布式锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、定义注解类
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public@interfaceDistributedLock{
//锁名称
StringlockName()default"";
//释放时间
longreleaseTime()default5*1000;
//时间单位
TimeUnittimeUnit()defaultTimeUnit.MILLISECONDS;
}
2、定义切面拦截DistributedLock注解
@Aspect
@Component
@Slf4j
publicclassDistributedLockAspect{
@Autowired
privateRedissonClientredissonClient;
//这里需要修改对应的包名
@Pointcut("@annotation(com.utils.annotation.DistributedLock)")
publicvoidRlockAspect(){
}
@Around("RlockAspect()")
publicObjectarround(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{
Objectobject=null;
RLocklock=null;
log.info("rlockAspectstart");
try{
DistributedLockrlockInfo=getRlockInfo(proceedingJoinPoint);
StringlockKey=getLocalKey(proceedingJoinPoint,rlockInfo);
lock=redissonClient.getLock(lockKey);
if(lock!=null){
finalbooleanstatus=lock.tryLock(rlockInfo.releaseTime(),rlockInfo.timeUnit());
if(status){
object=proceedingJoinPoint.proceed();
}
}else{
log.info("未获取到锁:{}",lockKey);
}
}finally{
//当前线程获取到锁再释放锁
if(lock!=null&&lock.isHeldByCurrentThread()){
lock.unlock();
}
}
returnobject;
}
publicDistributedLockgetRlockInfo(ProceedingJoinPointproceedingJoinPoint){
MethodSignaturemethodSignature=(MethodSignature)proceedingJoinPoint.getSignature();
returnmethodSignature.getMethod().getAnnotation(DistributedLock.class);
}
/**
*获取redislockkey
*
*@paramproceedingJoinPoint
*@return
*/
publicStringgetLocalKey(ProceedingJoinPointproceedingJoinPoint,DistributedLockrlockInfo){
StringBuilderlocalKey=newStringBuilder("Rlock");
finalObject[]args=proceedingJoinPoint.getArgs();
StringbusinessNo="";
//如果没有设置锁值
if(StringUtils.isNotEmpty(rlockInfo.lockName())){
businessNo=rlockInfo.lockName();
}else{
MethodSignaturemethodSignature=(MethodSignature)proceedingJoinPoint.getSignature();
Class[]parameters=methodSignature.getParameterTypes();
StringmethodName=methodSignature.getMethod().getName();
if(parameters!=null){
for(inti=0;i
3、使用方法:在需要用分布式锁的方法上面加@DistributedLock注解即可
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。