利用SQL实现简单的分布式锁
利用SQL实现简单的分布式锁
分布式锁和普通锁的主要区别在于参与主体跨不同节点,因此需要考虑到节点失效和网络故障的问题。搞清楚问题要点,可以用各种不同的东西去实现,比如Redis,ZooKeeper等。但是其实用SQL实现也是非常容易的,下面以PostgreSQL为例进行说明。1. 方法1:会话锁
利用PostgreSQL中特有的排他会话级别咨询锁。pg_advisory_lock(key bigint)
pg_advisory_unlock(key bigint)
pg_try_advisory_lock(key bigint)
详细参考: http://www.postgres.cn/docs/9.4/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS-TABLE
这种锁是会话级的,在释放锁之前,锁的获得得者必须一直持有这个会话,也就是连接,否则锁就会被释放。
这个特性自然而然地解决了锁的获得者发生故障时锁的释放问题。
但是,对于需要长时间持有的锁,它会产生长连接,而数据库的连接是比较耗资源的,往大了配一般也就几千个,这是需要注意的地方。
另外一个需要考虑的问题是,当网络或节点发生故障时连接的两端未必能立刻感知到,因此TCP的KeepAlive是必须的,幸好PostgreSQL的客户端和服务端都支持这个设置。
下面是服务端的参数:
tcp_keepalives_idle
tcp_keepalives_interval
tcp_keepalives_count
2. 方法2:期限锁
锁对象是持久的,为防止拿到锁的客户端奔溃导致锁无法释放,每个锁都有一个过期期限。在PostgreSQL中可以按下面的方式实现
建表
- postgres=# create table distlock(id int primary key,expired_time interval,owner text,ts timestamptz);
- CREATE TABLE
- postgres=# insert into distlock(id) values(1);
- INSERT 0 1
加锁和续期
- postgres=# update distlock set owner='node1',ts=now(),expired_time=interval '20 second' where id=1 and (owner='node1' or owner is null or now() > ts + expired_time);
- UPDATE 1
此时,其它客户端取锁会失败
- postgres=# update distlock set owner='node2',ts=now(),expired_time=interval '20 second' where id=1 and (owner='node2' or owner is null or now() > ts + expired_time);
- UPDATE 0
等锁过期后取锁成功
- postgres=# update distlock set owner='node2',ts=now(),expired_time=interval '20 second' where id=1 and (owner='node2' or owner is null or now() > ts + expired_time);
- UPDATE 1
释放锁
- postgres=# update distlock set owner=null,ts=now() where id=1 and owner='node2';
- UPDATE 1
3. 总结
可以看到用关系数据库实现分布式锁并不复杂。尤其上面基于表实现的锁辅以靠谱的HA部署可以保障锁信息的持久性和不丢失,但用表更新实现锁毕竟比较重,不适合对锁的性能要求非常高的场景。
Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Motorola has released countless devices this year, although only two of them are foldables. For context, while most of the world has received the pair as the Razr 50 and Razr 50 Ultra, Motorola offers them in North America as the Razr 2024 and Razr 2

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li
