分布式锁系统设计

nber1994

All
Posts
Categories
Tags
About

分布式锁系统设计

    ❐sysDesign


分布式锁的一些原则

常见实现方式

mysql实现

CREATE TABLE `resourceLock` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `resource_name` varchar(128) NOT NULL DEFAULT '' COMMENT '资源名字',
    `node_info` varchar(128) DEFAULT NULL COMMENT '节点信息',
    `count` int(11) NOT NULL DEFAULT '0' COMMENT '锁的次数 (可重入)',
    `desc` varchar(128) DEFAULT NULL COMMENT '资源描述',
    `mtime` timestamp NULL DEFAULT NULL,
    `ctime` timestamp NULL DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uniq_resource` (`resource_name`)
) ENGINE=InnoDB DEFAULT CAHRSET=utf8mb4;

加锁

查询xxx资源是否是当前节点所有,如果有的话则增加count

transaction begin
res = select * from resourceLock where resource_name = xxx for update;
if res == nil 
    insert ....
    return true
if node_info == myNode 
    //更新次数
    update resourceLock set count = count+1 where resource_name = xxx
    commit
    return true
else
    commit
    return false

解锁

如果count为1则删除,大于一则减一

transaction begin
select * from resourceLock where resource_name=xxx for update;
if count > 1
    update count = count-1
else 
    delete 

锁超时

惰性解锁

可以在试图加锁的时候,首先检测锁是否超时,超时则解锁

定时解锁

离线的脚本来定时的去解锁超时的锁

小结