欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2020年02月27日 13:00:21   作者:min.jiang  
這篇文章主要介紹了Java基于注解實(shí)現(xiàn)的鎖實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

背景

某些場(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)文章

最新評(píng)論