亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

Java基于注解實(shí)現(xiàn)的鎖實(shí)例解析

瀏覽:70日期:2022-09-05 10:01:22

背景

某些場景下,有可能一個(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被阻塞。

Java基于注解實(shí)現(xiàn)的鎖實(shí)例解析

分布式版本

分布式的除了鎖機(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)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 亚洲精品一区二区三区美女 | 欧美日韩国产一区二区 | 在线观看国产麻豆 | 亚洲综合久久久 | 国产黄色免费网站 | 欧美成人免费草草影院 | 日韩a无吗一区二区三区 | 九一视频在线 | 一级黄色影院 | 成人欧美一区二区三区白人 | 成人免费黄色大片 | 视频在线二区 | 亚洲啪啪 | 亚洲一区二区三区四区在线观看 | 日本大片久久久高清免费看 | 一级片黄色片 | 正在播放淫亚洲 | 久久久久欧美国产精品 | xxxx鞠婧祎xxxx网站视频观看 | 永久免费看黄在线播放 | 午夜男人女人爽爽爽视频 | 亚洲综合99| 成人网址在线观看 | 久草久爱 | 99re在线精品视频 | 看片地址 | 欧美夜夜片a | 91蝌蚪视频在线观看 | 国产三级做爰高清视频a | 日本xxx免费视频 | 免费观看欧美一级毛片 | 国产真实女人一级毛片 | 麻豆视频污 | 久久第一页| 国产3p在线播放 | 国产在线观a免费观看 | 日韩欧美精品综合久久 | 欧美色xx | 二级黄绝大片中国免费视频0 | 日韩视频网 | 日本视频高清免费观看xxx |