如何使用mysql实现分布式锁

打印 上一主题 下一主题

主题 847|帖子 847|积分 2541

如何使用mysql实现可重入的分布式锁

目录


  • 什么是分布式锁?
  • 如何实现分布式锁?
  • 定义分布式表结构
  • 定义锁统一接口
  • 使用mysql来实现分布式锁
    ① 生成线程标记ID
    ② 加锁
    ③ 解锁
    ④ 重置锁
  • 写在最后
1. 什么是分布式锁?

百度百科:分布式锁是控制分布式系统之间同步访问共享资源的一种方式。
ㅤ如引用所述,分布式锁是一种用于在分布式系统中对资源进行同步访问的机制。在分布式系统中,多个节点同时访问某个共享资源时,需要确保资源的一致性和正确性。分布式锁可以通过协调多个节点之间的操作,保证在同一时间内只有一个节点能够访问该资源,从而避免竞态条件和数据不一致的问题。
2. 如何实现分布式锁?

基于数据库的分布式锁:使用数据库的事务机制来实现分布式锁,通过在数据库中创建一个唯一约束或者加锁表来保证同一时间只有一个节点能够获得锁。
基于共享存储的分布式锁:使用共享存储如Redis、ZooKeeper等来实现分布式锁,通过在共享存储中创建占位节点或者临时节点来表示锁的状态。
基于乐观锁的分布式锁:通过使用版本号或者时间戳等方式,在修改资源时判断是否被其他节点修改,从而实现资源的同步访问。
ㅤ分布式锁的实现需要考虑各种复杂条件,如锁的可重入性、死锁的处理、锁的过期时间等。因此,使用分布式锁时需要谨慎设计和合理选择实现方式,以保证系统的性能和可靠性。
3. 定义分布式表结构
  1. create table if not exists t_distributed_lock
  2. (
  3.     id              int auto_increment primary key,
  4.     lock_key        varchar(255) default '' not null comment '锁key',
  5.     thread_ident    varchar(255) default '' not null comment '线程标识',
  6.     timeout         mediumtext              not null comment '超时时间',
  7.     reentrant_count int          default 0  not null comment '可重入次数',
  8.     version         int          default 1  not null comment '版本号(用于乐观锁)'
  9. )
  10.     comment '分布式锁';
复制代码
4. 定义锁统一接口
  1. public interface ILock<T> {
  2.     /**
  3.      * 加锁(支持可重入)
  4.      *
  5.      * @param lockKey                   锁key
  6.      * @param lockTimeoutMillisecond    锁超时时间(1.锁不是无限存在的 2.为可能存在的死锁做兜底)
  7.      * @param getLockTimeoutMillisecond 获取锁的超时时间(获取锁的时间应该也是有限的)
  8.      */
  9.     boolean lock(String lockKey, long lockTimeoutMillisecond, long getLockTimeoutMillisecond);
  10.     /**
  11.      * 解锁
  12.      *
  13.      * @param lockKey 锁key
  14.      */
  15.     boolean unLock(String lockKey);
  16.     /**
  17.      * 重置锁
  18.      *
  19.      * @param t 锁对象
  20.      */
  21.     boolean resetLock(T t);
  22. }
复制代码
ㅤ定义关于锁的统一接口,对参数类型进行泛化。
5. 使用mysql来实现分布式锁

5.1 生成线程标记ID
  1. import cn.hutool.core.lang.UUID;
  2. import cn.wxroot.learn.distributedLock.mysql.entity.DistributedLock;
  3. import cn.wxroot.learn.distributedLock.mysql.mapper.DistributedLockMapper;
  4. import cn.wxroot.learn.distributedLock.ILock;
  5. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  6. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.springframework.stereotype.Service;
  10. import java.util.Objects;
  11. @Service
  12. @Slf4j
  13. public class MysqlLock extends ServiceImpl<DistributedLockMapper, DistributedLock> implements ILock<DistributedLock> {
  14.     ThreadLocal<String> threadIdent = new ThreadLocal<>();
  15.     /**
  16.      * 获取线程标记ID
  17.      *
  18.      * @return 线程标记ID
  19.      */
  20.     private String getThreadIdentId() {
  21.         if (Objects.isNull(threadIdent.get())) {
  22.             threadIdent.set(UUID.randomUUID().toString());
  23.         }
  24.         return threadIdent.get();
  25.     }
  26.     // 加锁、解锁、重置锁
  27. }
复制代码
ㅤ创建mysql方式的锁实现类。方法getThreadIdentId()来生成线程的唯一标识。
5.1 加锁
  1.     @Override
  2.     public boolean lock(String lockKey, long lockTimeoutMillisecond, long getLockTimeoutMillisecond) {
  3.         boolean result = false;
  4.         long startTime = System.currentTimeMillis();
  5.         String threadIdentId = this.getThreadIdentId();
  6.         while (true) {
  7.             if (startTime + getLockTimeoutMillisecond < System.currentTimeMillis()) {
  8.                 log.info("获取锁超时!");
  9.                 break;
  10.             }
  11.             QueryWrapper<DistributedLock> distributedLockQueryWrapper = new QueryWrapper<>();
  12.             distributedLockQueryWrapper.lambda().eq(true, DistributedLock::getLockKey, lockKey);
  13.             DistributedLock distributedLock = this.getOne(distributedLockQueryWrapper);
  14.             if (Objects.nonNull(distributedLock)) {
  15.                 if (StringUtils.isNotEmpty(distributedLock.getThreadIdent())) {
  16.                     if (threadIdentId.equals(distributedLock.getThreadIdent())) {
  17.                         log.info("重入锁+1");
  18.                         distributedLock.setReentrantCount(distributedLock.getReentrantCount() + 1);
  19.                         distributedLock.setTimeout(System.currentTimeMillis() + lockTimeoutMillisecond);
  20.                         this.updateById(distributedLock);
  21.                         result = true;
  22.                         break;
  23.                     } else {
  24.                         // 其他线程锁定了该lockKey,需要等待
  25.                         if (distributedLock.getTimeout() < System.currentTimeMillis()) {
  26.                             this.resetLock(distributedLock);
  27.                         } else {
  28.                             try {
  29.                                 log.info("休眠");
  30.                                 Thread.sleep(100);
  31.                             } catch (InterruptedException ignored) {
  32.                             }
  33.                         }
  34.                     }
  35.                 } else {
  36.                     log.info("占用锁");
  37.                     distributedLock.setThreadIdent(threadIdentId);
  38.                     distributedLock.setReentrantCount(1);
  39.                     distributedLock.setTimeout(System.currentTimeMillis() + lockTimeoutMillisecond);
  40.                     this.updateById(distributedLock);
  41.                     result = true;
  42.                     break;
  43.                 }
  44.             } else {
  45.                 log.info("创建新记录");
  46.                 DistributedLock addDistributedLock = DistributedLock.builder()
  47.                         .lockKey(lockKey)
  48.                         .threadIdent(threadIdentId)
  49.                         .timeout(System.currentTimeMillis() + lockTimeoutMillisecond)
  50.                         .reentrantCount(1)
  51.                         .version(1)
  52.                         .build();
  53.                 this.save(addDistributedLock);
  54.                 result = true;
  55.                 break;
  56.             }
  57.         }
  58.         return result;
  59.     }
复制代码
ㅤ实现加锁的方法boolean lock(···)应考虑以下几点:
ㅤ1. 使用锁的时间应该有限的,即不能永久占有锁。
ㅤ2. 获取锁的过程应该是有限的,即指定时间内获取不到锁应该返回。
5.1 解锁
  1.     @Override
  2.     public boolean unLock(String lockKey) {
  3.         boolean result = false;
  4.         String threadIdentId = this.getThreadIdentId();
  5.         log.info("解锁");
  6.         QueryWrapper<DistributedLock> distributedLockQueryWrapper = new QueryWrapper<>();
  7.         distributedLockQueryWrapper.lambda().eq(true, DistributedLock::getLockKey, lockKey);
  8.         DistributedLock distributedLock = this.getOne(distributedLockQueryWrapper);
  9.         if (Objects.nonNull(distributedLock)) {
  10.             if (distributedLock.getThreadIdent().equals(threadIdentId)) {
  11.                 if (distributedLock.getReentrantCount() > 1) {
  12.                     distributedLock.setReentrantCount(distributedLock.getReentrantCount() - 1);
  13.                     this.updateById(distributedLock);
  14.                     result = true;
  15.                 } else {
  16.                     result = this.resetLock(distributedLock);
  17.                 }
  18.             }
  19.         }
  20.         return result;
  21.     }
复制代码
ㅤ基于可重入锁的特性,在进行解锁操作时,应该有所判断。
5.1 重置锁
  1.     @Override
  2.     public boolean resetLock(DistributedLock distributedLock) {
  3.         log.info("重置锁");
  4.         distributedLock.setThreadIdent("");
  5.         distributedLock.setReentrantCount(0);
  6.         this.updateById(distributedLock);
  7.         return true;
  8.     }
复制代码

转载请注明出处

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

曹旭辉

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表