Java注解如何基于Redission实现分布式锁
程序员文章站
2023-01-25 18:35:28
这篇文章主要介绍了java注解如何基于redission实现分布式锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、定义注解类...
这篇文章主要介绍了java注解如何基于redission实现分布式锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、定义注解类
@target({ elementtype.method }) @retention(retentionpolicy.runtime) @documented public @interface distributedlock { //锁名称 string lockname() default ""; //释放时间 long releasetime() default 5*1000; //时间单位 timeunit timeunit() default timeunit.milliseconds; }
2、定义切面拦截 distributedlock 注解
@aspect @component @slf4j public class distributedlockaspect { @autowired private redissonclient redissonclient; //这里需要修改对应的包名 @pointcut("@annotation(com.utils.annotation.distributedlock)") public void rlockaspect() { } @around("rlockaspect()") public object arround(proceedingjoinpoint proceedingjoinpoint) throws throwable { object object = null; rlock lock = null; log.info("rlockaspect start "); try { distributedlock rlockinfo = getrlockinfo(proceedingjoinpoint); string lockkey = getlocalkey(proceedingjoinpoint, rlockinfo); lock = redissonclient.getlock(lockkey); if (lock != null) { final boolean status = lock.trylock(rlockinfo.releasetime(), rlockinfo.timeunit()); if (status) { object = proceedingjoinpoint.proceed(); } } else { log.info("未获取到锁:{}", lockkey); } } finally { // 当前线程获取到锁再释放锁 if (lock != null && lock.isheldbycurrentthread()) { lock.unlock(); } } return object; } public distributedlock getrlockinfo(proceedingjoinpoint proceedingjoinpoint) { methodsignature methodsignature = (methodsignature) proceedingjoinpoint.getsignature(); return methodsignature.getmethod().getannotation(distributedlock.class); } /** * 获取redis lock key * * @param proceedingjoinpoint * @return */ public string getlocalkey(proceedingjoinpoint proceedingjoinpoint, distributedlock rlockinfo) { stringbuilder localkey = new stringbuilder("rlock"); final object[] args = proceedingjoinpoint.getargs(); string businessno = ""; // 如果没有设置锁值 if (stringutils.isnotempty(rlockinfo.lockname())) { businessno = rlockinfo.lockname(); } else { methodsignature methodsignature = (methodsignature) proceedingjoinpoint.getsignature(); class[] parameters = methodsignature.getparametertypes(); string methodname = methodsignature.getmethod().getname(); if (parameters != null) { for (int i = 0; i < parameters.length; i++) { class parameter = parameters[i]; if (parameter.getsimplename().equals("ndevice")) { ndevice de = (ndevice) args[i]; businessno = de.getuuid() + methodname; } if (parameter.getsimplename().equals("framebean")) { framebean de = (framebean) args[i]; businessno = de.getcolumn1() + methodname; } } // 如果没有获取到业务编号,则使用方法签名 if (stringutils.isempty(businessno)) { businessno = methodname; } } } return businessno; } }
3、使用方法:在需要用分布式锁的方法上面加 @distributedlock 注解即可
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。