Java基于注解實(shí)現(xiàn)的鎖實(shí)例解析
背景
某些場(chǎng)景下,有可能一個(gè)方法不能被并發(fā)執(zhí)行,有可能一個(gè)方法的特定參數(shù)不能被并發(fā)執(zhí)行。比如不能將一個(gè)消息發(fā)送多次,創(chuàng)建緩存最好只創(chuàng)建一次等等。為了實(shí)現(xiàn)上面的目標(biāo)我們就需要采用同步機(jī)制來(lái)完成,但同步的邏輯如何實(shí)現(xiàn)呢,是否會(huì)影響到原有邏輯呢?
嵌入式
這里講的嵌入式是說(shuō)獲取鎖以及釋放鎖的邏輯與業(yè)務(wù)代碼耦合在一起,又分分布式與單機(jī)兩種不同場(chǎng)景的不同實(shí)現(xiàn)。
單機(jī)版本
下面方法,每個(gè)productId不允許并發(fā)訪問(wèn),所以這里可以直接用synchronized來(lái)鎖定不同的參數(shù)。
@Service public class ProductAppService { public void invoke(Integer productId) { synchronized (productId) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print("productId:" + productId+" time:"+new Date()); } } }
測(cè)試腳本:三個(gè)相同的參數(shù)0,兩個(gè)不同的參數(shù)1和2,通過(guò)一個(gè)多線(xiàn)程的例子來(lái)模似。如果有并發(fā)請(qǐng)求的測(cè)試工具可能效果會(huì)更好。
private void testLock(){ ExecutorService executorService= Executors.newFixedThreadPool(5); executorService.submit(new Runnable() { @Override public void run() { productAppService.invoke2(0); } }); executorService.submit(new Runnable() { @Override public void run() { productAppService.invoke2(0); } }); executorService.submit(new Runnable() { @Override public void run() { productAppService.invoke2(0); } }); executorService.submit(new Runnable() { @Override public void run() { productAppService.invoke2(1); } }); executorService.submit(new Runnable() { @Override public void run() { productAppService.invoke2(2); } }); executorService.shutdown(); }
測(cè)試結(jié)果如下,0,1,2三個(gè)請(qǐng)求未被阻塞,后面的兩個(gè)0被阻塞。
分布式版本
分布式的除了鎖機(jī)制不同之外其它的測(cè)試方法相同,這里只貼出鎖的部分:
public void invoke2(Integer productId) { RLock lock=this.redissonService.getRedisson().getLock(productId.toString()); try { boolean locked=lock.tryLock(3000,500, TimeUnit.MILLISECONDS); if(locked){ Thread.sleep(1000); System.out.print("productId:" + productId+" time:"+new Date()); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }
嵌入式的缺點(diǎn)
比較明顯的就是鎖的邏輯與業(yè)務(wù)邏輯混合在一起,增加了程序復(fù)雜度而且也不利于鎖機(jī)制的更替。
注解式
能否將鎖的邏輯隱藏起來(lái),通過(guò)在特定方法上增加注解來(lái)實(shí)現(xiàn)呢?就像Spring Cache的應(yīng)用。當(dāng)然是可以的,這里我們只需要解決如下三個(gè)問(wèn)題:
定義注解
鎖一般有如下幾個(gè)屬性:
- key,鎖對(duì)象的標(biāo)識(shí),就是上面提到的方法的某些參數(shù)。一般由方法所屬類(lèi)的完全限定名,方法名以及指定的參數(shù)構(gòu)成。
- maximumWaiteTime,最大等待時(shí)間,避免線(xiàn)程死循環(huán)。
- expirationTime,鎖的生命周期,可以有效避免因特殊原因未釋放鎖導(dǎo)致其它線(xiàn)程永遠(yuǎn)獲取不到鎖的局面。
- timeUnit,配合上面兩個(gè)屬性使用,時(shí)間單位。
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RequestLockable { String[] key() default ""; long maximumWaiteTime() default 2000; long expirationTime() default 1000; TimeUnit timeUnit() default TimeUnit.MILLISECONDS; }
實(shí)現(xiàn)注解
由于我們的目標(biāo)是注解式鎖,這里通過(guò)AOP的方式來(lái)實(shí)現(xiàn),具體依賴(lài)AspectJ,創(chuàng)建一個(gè)攔截器:
public abstract class AbstractRequestLockInterceptor { protected abstract Lock getLock(String key); protected abstract boolean tryLock(long waitTime, long leaseTime, TimeUnit unit,Lock lock) throws InterruptedException; /** * 包的表達(dá)式目前還有待優(yōu)化 TODO */ @Pointcut("execution(* com.chanjet.csp..*(..)) && @annotation(com.chanjet.csp.product.core.annotation.RequestLockable)") public void pointcut(){} @Around("pointcut()") public Object doAround(ProceedingJoinPoint point) throws Throwable{ Signature signature = point.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); String targetName = point.getTarget().getClass().getName(); String methodName = point.getSignature().getName(); Object[] arguments = point.getArgs(); if (method != null && method.isAnnotationPresent(RequestLockable.class)) { RequestLockable requestLockable = method.getAnnotation(RequestLockable.class); String requestLockKey = getLockKey(method,targetName, methodName, requestLockable.key(), arguments); Lock lock=this.getLock(requestLockKey); boolean isLock = this.tryLock(requestLockable.maximumWaiteTime(),requestLockable.expirationTime(), requestLockable.timeUnit(),lock); if(isLock) { try { return point.proceed(); } finally { lock.unlock(); } } else { throw new RuntimeException("獲取鎖資源失敗"); } } return point.proceed(); } private String getLockKey(Method method,String targetName, String methodName, String[] keys, Object[] arguments) { StringBuilder sb = new StringBuilder(); sb.append("lock.").append(targetName).append(".").append(methodName); if(keys != null) { String keyStr = Joiner.on(".").skipNulls().join(keys); if(!StringUtils.isBlank(keyStr)) { LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); String[] parameters =discoverer.getParameterNames(method); ExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression(keyStr); EvaluationContext context = new StandardEvaluationContext(); int length = parameters.length; if (length > 0) { for (int i = 0; i < length; i++) { context.setVariable(parameters[i], arguments[i]); } } String keysValue = expression.getValue(context, String.class); sb.append("#").append(keysValue); } } return sb.toString(); } }
注意如下幾點(diǎn):
為什么會(huì)存在抽象方法?那是為下面的將注解機(jī)制與具體的鎖實(shí)現(xiàn)解耦服務(wù)的,目的是希望注解式鎖能夠得到復(fù)用也便于擴(kuò)展。鎖的key生成規(guī)則是什么?前綴一般是方法所在類(lèi)的完全限定名,方法名稱(chēng)以及spel表達(dá)式來(lái)構(gòu)成,避免重復(fù)。SPEL表達(dá)式如何支持?
LocalVariableTableParameterNameDiscoverer它在Spring MVC解析Controller的參數(shù)時(shí)有用到,可以從一個(gè)Method對(duì)象中獲取參數(shù)名稱(chēng)列表。
SpelExpressionParser是標(biāo)準(zhǔn)的spel解析器,利用上面得來(lái)的參數(shù)名稱(chēng)列表以及參數(shù)值列表來(lái)獲取真實(shí)表達(dá)式。
問(wèn)題
基于aspectj的攔截器,@Pointcut中的參數(shù)目前未找到動(dòng)態(tài)配置的方法,如果有解決方案的可以告訴我。
將注解機(jī)制與具體的鎖實(shí)現(xiàn)解耦
注解式鎖理論上應(yīng)該與具體的鎖實(shí)現(xiàn)細(xì)節(jié)分離,客戶(hù)端可以任意指定鎖,可以是單機(jī)下的ReentrantLock也可以是基于redis的分布式鎖,當(dāng)然也可以是基于zookeeper的鎖,基于此目的上面我們創(chuàng)建的AbstractRequestLockInterceptor這個(gè)攔截器是個(gè)抽象類(lèi)??聪禄趓edis的分布式鎖的子類(lèi)實(shí)現(xiàn):
@Aspect public class RedisRequestLockInterceptor extends AbstractRequestLockInterceptor { @Autowired private RedissonService redissonService; private RedissonClient getRedissonClient(){ return this.redissonService.getRedisson(); } @Override protected Lock getLock(String key) { return this.getRedissonClient().getLock(key); } @Override protected boolean tryLock(long waitTime, long leaseTime, TimeUnit unit,Lock lock) throws InterruptedException { return ((RLock)lock).tryLock(waitTime,leaseTime,unit); } }
注解式鎖的應(yīng)用
只需要在需要同步的方法上增加@RequestLockable,然后根據(jù)需要指定或者不指定key,也可以根據(jù)實(shí)際場(chǎng)景配置鎖等待時(shí)間以及鎖的生命周期。
@RequestLockable(key = {"#productId"}) public void invoke3(Integer productId) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print("productId:" + productId+" time:"+new Date()); }
當(dāng)然為了攔截器生效,我們需要在配置文件中配置上攔截器。
<bean class="com.product.api.interceptor.RedisRequestLockInterceptor"></bean> <aop:aspectj-autoproxy proxy-target-class="true"/>
注解式鎖的優(yōu)點(diǎn):鎖的邏輯與業(yè)務(wù)代碼完全分離,降低了復(fù)雜度。靈活的spel表達(dá)式可以靈活的構(gòu)建鎖的key。支持多種鎖,可以隨意切換而不影響業(yè)務(wù)代碼。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java?synchornized與ReentrantLock處理并發(fā)出現(xiàn)的錯(cuò)誤
synchronized機(jī)制提供了對(duì)每個(gè)對(duì)象相關(guān)的隱式監(jiān)視器鎖,并強(qiáng)制所有鎖的獲取和釋放都必須在同一個(gè)塊結(jié)構(gòu)中。當(dāng)獲取了多個(gè)鎖時(shí),必須以相反的順序釋放。即synchronized對(duì)于鎖的釋放是隱式的2023-01-01spring boot下 500 404 錯(cuò)誤頁(yè)面處理的方法
本篇文章主要介紹了spring boot下 500 404 錯(cuò)誤頁(yè)面處理的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04java使用poi讀取excel內(nèi)容方法實(shí)例
本文介紹java使用poi讀取excel內(nèi)容的實(shí)例,大家參考使用吧2014-01-01java synchronized加載加鎖-線(xiàn)程可重入詳解及實(shí)例代碼
這篇文章主要介紹了java synchronized加載加鎖-線(xiàn)程可重入詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-02-02jxl 導(dǎo)出數(shù)據(jù)到excel的實(shí)例講解
下面小編就為大家分享一篇jxl 導(dǎo)出數(shù)據(jù)到excel的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-12-12springboot如何使用thymeleaf模板訪問(wèn)html頁(yè)面
springboot中推薦使用thymeleaf模板,使用html作為頁(yè)面展示。那么如何通過(guò)Controller來(lái)訪問(wèn)來(lái)訪問(wèn)html頁(yè)面呢?下面通過(guò)本文給大家詳細(xì)介紹,感興趣的朋友跟隨腳本之家小編一起看看吧2018-05-05Java BufferedWriter BufferedReader 源碼分析
本文是關(guān)于Java BufferedWriter ,BufferedReader 簡(jiǎn)介、分析源碼 對(duì)Java IO 流深入了解,希望看到的同學(xué)對(duì)你有所幫助2016-07-07java 遍歷request中的所有表單數(shù)據(jù)的實(shí)例代碼
下面小編就為大家?guī)?lái)一篇java 遍歷request中的所有表單數(shù)據(jù)的實(shí)例代碼。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09Java并發(fā)編程回環(huán)屏障CyclicBarrier
這篇文章主要介紹了Java并發(fā)編程回環(huán)屏障CyclicBarrier,文章繼續(xù)上文所介紹的Java并發(fā)編程同步器CountDownLatch展開(kāi)主題相關(guān)內(nèi)容,需要的小伙伴可以參考一下2022-04-04MVC頁(yè)面之間參數(shù)傳遞實(shí)現(xiàn)過(guò)程圖解
這篇文章主要介紹了MVC頁(yè)面之間參數(shù)傳遞實(shí)現(xiàn)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11