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

背景

公司主營業(yè)務(wù):成都網(wǎng)站制作、成都做網(wǎng)站、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。成都創(chuàng)新互聯(lián)是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會用頭腦與智慧不斷的給客戶帶來驚喜。成都創(chuàng)新互聯(lián)推出蘆山免費(fèi)做網(wǎng)站回饋大家。

某些場景下,有可能一個方法不能被并發(fā)執(zhí)行,有可能一個方法的特定參數(shù)不能被并發(fā)執(zhí)行。比如不能將一個消息發(fā)送多次,創(chuàng)建緩存最好只創(chuàng)建一次等等。為了實(shí)現(xiàn)上面的目標(biāo)我們就需要采用同步機(jī)制來完成,但同步的邏輯如何實(shí)現(xiàn)呢,是否會影響到原有邏輯呢?

嵌入式

這里講的嵌入式是說獲取鎖以及釋放鎖的邏輯與業(yè)務(wù)代碼耦合在一起,又分分布式與單機(jī)兩種不同場景的不同實(shí)現(xiàn)。

單機(jī)版本

下面方法,每個productId不允許并發(fā)訪問,所以這里可以直接用synchronized來鎖定不同的參數(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());
    }
  }
}

測試腳本:三個相同的參數(shù)0,兩個不同的參數(shù)1和2,通過一個多線程的例子來模似。如果有并發(fā)請求的測試工具可能效果會更好。

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三個請求未被阻塞,后面的兩個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)然是可以的,這里我們只需要解決如下三個問題:

定義注解

鎖一般有如下幾個屬性:

  • key,鎖對象的標(biāo)識,就是上面提到的方法的某些參數(shù)。一般由方法所屬類的完全限定名,方法名以及指定的參數(shù)構(gòu)成。
  • maximumWaiteTime,最大等待時間,避免線程死循環(huán)。
  • expirationTime,鎖的生命周期,可以有效避免因特殊原因未釋放鎖導(dǎo)致其它線程永遠(yuǎn)獲取不到鎖的局面。
  • timeUnit,配合上面兩個屬性使用,時間單位。
@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)建一個攔截器:

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):

為什么會存在抽象方法?那是為下面的將注解機(jī)制與具體的鎖實(shí)現(xiàn)解耦服務(wù)的,目的是希望注解式鎖能夠得到復(fù)用也便于擴(kuò)展。鎖的key生成規(guī)則是什么?前綴一般是方法所在類的完全限定名,方法名稱以及spel表達(dá)式來構(gòu)成,避免重復(fù)。SPEL表達(dá)式如何支持?

LocalVariableTableParameterNameDiscoverer它在Spring MVC解析Controller的參數(shù)時有用到,可以從一個Method對象中獲取參數(shù)名稱列表。
SpelExpressionParser是標(biāo)準(zhǔn)的spel解析器,利用上面得來的參數(shù)名稱列表以及參數(shù)值列表來獲取真實(shí)表達(dá)式。

問題

基于aspectj的攔截器,@Pointcut中的參數(shù)目前未找到動態(tài)配置的方法,如果有解決方案的可以告訴我。

將注解機(jī)制與具體的鎖實(shí)現(xiàn)解耦

注解式鎖理論上應(yīng)該與具體的鎖實(shí)現(xiàn)細(xì)節(jié)分離,客戶端可以任意指定鎖,可以是單機(jī)下的ReentrantLock也可以是基于redis的分布式鎖,當(dāng)然也可以是基于zookeeper的鎖,基于此目的上面我們創(chuàng)建的AbstractRequestLockInterceptor這個攔截器是個抽象類??聪禄趓edis的分布式鎖的子類實(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í)際場景配置鎖等待時間以及鎖的生命周期。

  @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ù)代碼。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當(dāng)前文章:Java基于注解實(shí)現(xiàn)的鎖實(shí)例解析
本文地址:http://muchs.cn/article38/ihedpp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、網(wǎng)站建設(shè)、網(wǎng)站制作網(wǎng)站策劃、網(wǎng)頁設(shè)計公司品牌網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計