Java基于注解實(shí)現(xiàn)的鎖實(shí)例解析
背景
某些場景下,有可能一個(gè)方法不能被并發(fā)執(zhí)行,有可能一個(gè)方法的特定參數(shù)不能被并發(fā)執(zhí)行。比如不能將一個(gè)消息發(fā)送多次,創(chuàng)建緩存最好只創(chuàng)建一次等等。為了實(shí)現(xiàn)上面的目標(biāo)我們就需要采用同步機(jī)制來完成,但同步的邏輯如何實(shí)現(xiàn)呢,是否會(huì)影響到原有邏輯呢?
嵌入式
這里講的嵌入式是說獲取鎖以及釋放鎖的邏輯與業(yè)務(wù)代碼耦合在一起,又分分布式與單機(jī)兩種不同場景的不同實(shí)現(xiàn)。
單機(jī)版本
下面方法,每個(gè)productId不允許并發(fā)訪問,所以這里可以直接用synchronized來鎖定不同的參數(shù)。
@Servicepublic 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()); } }}
測試腳本:三個(gè)相同的參數(shù)0,兩個(gè)不同的參數(shù)1和2,通過一個(gè)多線程的例子來模似。如果有并發(fā)請求的測試工具可能效果會(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();}
測試結(jié)果如下,0,1,2三個(gè)請求未被阻塞,后面的兩個(gè)0被阻塞。
分布式版本
分布式的除了鎖機(jī)制不同之外其它的測試方法相同,這里只貼出鎖的部分:
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ī)制的更替。
注解式
能否將鎖的邏輯隱藏起來,通過在特定方法上增加注解來實(shí)現(xiàn)呢?就像Spring Cache的應(yīng)用。當(dāng)然是可以的,這里我們只需要解決如下三個(gè)問題:
定義注解
鎖一般有如下幾個(gè)屬性:
key,鎖對象的標(biāo)識(shí),就是上面提到的方法的某些參數(shù)。一般由方法所屬類的完全限定名,方法名以及指定的參數(shù)構(gòu)成。 maximumWaiteTime,最大等待時(shí)間,避免線程死循環(huán)。 expirationTime,鎖的生命周期,可以有效避免因特殊原因未釋放鎖導(dǎo)致其它線程永遠(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)是注解式鎖,這里通過AOP的方式來實(shí)現(xiàn),具體依賴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ī)則是什么?前綴一般是方法所在類的完全限定名,方法名稱以及spel表達(dá)式來構(gòu)成,避免重復(fù)。SPEL表達(dá)式如何支持?
LocalVariableTableParameterNameDiscoverer它在Spring MVC解析Controller的參數(shù)時(shí)有用到,可以從一個(gè)Method對象中獲取參數(shù)名稱列表。SpelExpressionParser是標(biāo)準(zhǔn)的spel解析器,利用上面得來的參數(shù)名稱列表以及參數(shù)值列表來獲取真實(shí)表達(dá)式。
問題
基于aspectj的攔截器,@Pointcut中的參數(shù)目前未找到動(dòng)態(tài)配置的方法,如果有解決方案的可以告訴我。
將注解機(jī)制與具體的鎖實(shí)現(xiàn)解耦
注解式鎖理論上應(yīng)該與具體的鎖實(shí)現(xiàn)細(xì)節(jié)分離,客戶端可以任意指定鎖,可以是單機(jī)下的ReentrantLock也可以是基于redis的分布式鎖,當(dāng)然也可以是基于zookeeper的鎖,基于此目的上面我們創(chuàng)建的AbstractRequestLockInterceptor這個(gè)攔截器是個(gè)抽象類。看下基于redis的分布式鎖的子類實(shí)現(xiàn):
@Aspectpublic 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í)際場景配置鎖等待時(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- />
注解式鎖的優(yōu)點(diǎn):鎖的邏輯與業(yè)務(wù)代碼完全分離,降低了復(fù)雜度。靈活的spel表達(dá)式可以靈活的構(gòu)建鎖的key。支持多種鎖,可以隨意切換而不影響業(yè)務(wù)代碼。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼2. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)3. XML入門的常見問題(四)4. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法5. 詳解瀏覽器的緩存機(jī)制6. ASP基礎(chǔ)知識(shí)VBScript基本元素講解7. XHTML 1.0:標(biāo)記新的開端8. XML解析錯(cuò)誤:未組織好 的解決辦法9. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究10. 利用CSS3新特性創(chuàng)建透明邊框三角
