夜雨聆风学习资料网

ARTICLE · 1392058

拒绝模板代码!@Lock解决并发问题

拒绝模板代码!@Lock解决并发问题
《Spring Boot 3实战案例锦集》PDF电子书已更新至130篇!
🎉🎉《Spring Boot实战案例合集》目前已更新236个案例,我们将持续不断的更新。文末有电子书目录。→ 现在就订阅合集

环境:Spring Boot 3.5.0


1. 简介

在实际业务开发中,并发问题一直是绕不开的话题。当多个请求同时修改同一份数据时,如果没有合理的控制机制,很容易出现数据覆盖、状态错乱等问题。

很多开发者第一时间会想到手写锁,通过 synchronized、Lock 等方式解决,但随着业务复杂度提升,大量重复的锁代码不仅难维护,也容易埋下新的问题。如下示例代码:

RLock lock = redisson.getLock("myLock");// 1. 方式1// 传统锁定方法lock.lock();// 或者获取锁,并在10秒后自动解锁// 2. 方式2// lock.lock(10, TimeUnit.SECONDS);// 3. 方式3// 或者等待获取锁最多100秒,并在10秒后自动解锁boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);if (res) {  try {    // 业务代码  } finally {    lock.unlock();  }}

本篇文章,我们将通过自定义 @Lock 更直接的并发控制方式(不用再写如上的模版代码),通过声明式配置处理资源竞争问题。

2.实战案例
2.1 定义注解&接口
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface Lock {  String key() ;}
定义Lock接口
public interface PackLock extends Lock {  @Override  default void lockInterruptibly() throws InterruptedException {  }  @Override  default boolean tryLock() {    return false;  }  @Override  default boolean tryLock(long time, TimeUnit unit) throws InterruptedException {    return false;  }  @Override  default Condition newCondition() {    return null;  }}
JVM级锁实现
public class ReentrantPackLock implements PackLock {  private final ReentrantLock lock;  private final LockProperties lockProperties ;  publicReentrantPackLock(LockProperties lockProperties) {    this.lock = new ReentrantLock();    this.lockProperties = lockProperties ;  }  @Override  publicvoidlock() {    lock.lock();  }  @Override  publicvoidlockInterruptibly() throws InterruptedException {    lock.lockInterruptibly();  }  @Override  public boolean tryLock() {    try {      return lock.tryLock(this.lockProperties.time(), this.lockProperties.unit());    } catch (InterruptedException e) {      Thread.currentThread().interrupt();      throw new RuntimeException(e) ;    }  }  @Override  public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {    return lock.tryLock(time, unit);  }  @Override  publicvoidunlock() {    lock.unlock();  }  @Override  public Condition newCondition() {    return lock.newCondition();  }}
Redis分布式锁实现
public class RedissonPackLock implements PackLock {  private final RLock lock;  private final LockProperties lockProperties;  publicRedissonPackLock(RedissonClient redissonClient, LockProperties lockProperties, Lock annotation) {    this.lockProperties = lockProperties ;    this.lock = redissonClient.getLock(annotation.key()) ;  }  @Override  publicvoidlock() {    lock.lock();  }  @Override  publicvoidlockInterruptibly() throws InterruptedException {    lock.lockInterruptibly();  }  @Override  public boolean tryLock() {    try {      return lock.tryLock(this.lockProperties.time(), this.lockProperties.unit());    } catch (InterruptedException e) {      Thread.currentThread().interrupt();      throw new RuntimeException(e) ;    }  }  @Override  public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {    return lock.tryLock(time, unit);  }  @Override  publicvoidunlock() {    lock.unlock();  }  @Override  public Condition newCondition() {    throw new UnsupportedOperationException("Redisson distributed lock does not support Condition") ;  }}
锁配置
@ConfigurationProperties(prefix = "pack.lock")public record LockProperties(@DefaultValue("LOCAL") LockType type, String prefix, @DefaultValue("-1") Long time, @DefaultValue("") TimeUnit unit) {  public enum LockType {    LOCAL, REDIS  }}
2.2 切面定义
public class LockAdvisor implements PointcutAdvisor {  private final Map<String, PackLock> localLockCache = new ConcurrentHashMap<>();  private final LockProperties lockProperties ;  private final RedissonClient redissonClient ;  public LockAdvisor(LockProperties lockProperties, RedissonClient redissonClient) {    this.lockProperties = lockProperties;    this.redissonClient = redissonClient;  }  @Override  public Advice getAdvice() {    return new LockInterceptor(this.lockProperties, this.redissonClient) ;  }  @Override  public Pointcut getPointcut() {    return new StaticMethodMatcherPointcut() {      @Override      public boolean matches(Method method, Class<?> targetClass) {        return method.isAnnotationPresent(Lock.class) ;      }    } ;  }  public class LockInterceptor implements MethodInterceptor {    private final LockProperties lockProperties ;    private final RedissonClient redissonClient ;    public LockInterceptor(LockProperties lockProperties, RedissonClient redissonClient) {      this.lockProperties = lockProperties;      this.redissonClient = redissonClient;    }    @Override    public Object invoke(MethodInvocation invocation) throws Throwable {      Lock annotation = invocation.getMethod().getAnnotation(Lock.class) ;      if (annotation == null) {        return invocation.proceed() ;      }      LockType type = this.lockProperties.type() ;      PackLock packLock = null ;      if (type == LockType.LOCAL) {        packLock = localLockCache.computeIfAbsent(annotation.key(), k -> new ReentrantPackLock(lockProperties));      } else {        packLock = new RedissonPackLock(redissonClient, lockProperties, annotation) ;      }      packLock.lock() ;       try {        return invocation.proceed() ;      } finally {        packLock.unlock() ;      }    }  }}
定义BeanPostprocessor
public class LockProxyCreator implements BeanPostProcessor, Ordered {  private final LockAdvisor lockAdvisor ;  public LockProxyCreator(LockProperties lockProperties, RedissonClient redissonClient) {    this.lockAdvisor = new LockAdvisor(lockProperties, redissonClient) ;  }  @Override  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean) ;    boolean needCreator = false ;    Method[] methods = targetClass.getDeclaredMethods() ;    for (Method method : methods) {      if (Modifier.isPublic(method.getModifiers()) &&           method.isAnnotationPresent(Lock.class)) {        needCreator = true ;        break ;      }    }    if (!needCreator) {      return bean ;    }    if (AopUtils.isAopProxy(bean)) {      Advised advised = (Advised) bean ;      advised.addAdvisor(0, this.lockAdvisor);      return bean ;    }    ProxyFactory proxyFactory = new ProxyFactory();    proxyFactory.setTarget(bean);    proxyFactory.setExposeProxy(true);    proxyFactory.setProxyTargetClass(true) ;    proxyFactory.addAdvisor(this.lockAdvisor);    return proxyFactory.getProxy();  }  @Override  public int getOrder() {    return Ordered.LOWEST_PRECEDENCE ;  }}
2.3 测试
不加锁测试
@Transactionalpublic void deduct(Long stockId, Integer deductNum) {  this.stockRepository.findById(stockId).ifPresent(stock -> {    if (stock.getAmount() >= deductNum) {      int ret = stockRepository.deductStock(stockId, deductNum);      System.err.println("%s - %s".formatted(Thread.currentThread().getName(), ret > 0 ? "成功购买" : "库存不足")) ;    }  }) ;}
测试用例
@Testpublic void testDeduct() throws Exception {  final int COUNT = 30 ;  Thread[] threads = new Thread[COUNT] ;  CountDownLatch cdl = new CountDownLatch(COUNT) ;  CyclicBarrier cb = new CyclicBarrier(COUNT) ;  for (int i = 0; i < COUNT; i++) {    threads[i] = new Thread(() -> {      try {cb.await() ;} catch (Exception e) {}      stockService.deduct(1L, 10) ;      cdl.countDown() ;    }) ;  }  for (int i = 0; i < COUNT; i++) {    threads[i].start();   }  cdl.await(); }
执行结果
修改Service方法添加@Lock注解
@Transactional@Lock(key = "sss")public void deduct(Long stockId, Integer deductNum)
执行结果
以上是本篇文章的全部内容,如对你有帮助帮忙点赞+转发+收藏
无需额外服务!用DJL在Java中直接跑本地大模型

优雅!Chain 结合 Spring Boot 轻松实现强大的责任链模式

动态扩展能力!Spring Boot 一个强大实用的接口

基于 Spring Boot 解决并发安全更新的5种方案

优雅!基于Spring Boot字段加密后的模糊查询,支持MyBatis, JPA

自己动手实现Agent统计API接口调用耗时

确保Spring Boot定时任务只执行一次方案

禁止 POST 查数据!Spring Boot 支持 QUERY 请求

一行注解!Spring Boot 使用内置工具实现方法监控

事务外挂!原生JDBC完美感知 Spring Boot 事务

回首页,搜索你想要的文档

在首页搜索框输入关键词,快速定位资料

文库首页搜索指引 立即搜索

相关学习资料