Table of Contents
利用SQL实现简单的分布式锁
1. 方法1:会话锁
2. 方法2:期限锁
3. 总结
Home php教程 php手册 利用SQL实现简单的分布式锁

利用SQL实现简单的分布式锁

Jun 13, 2016 am 08:42 AM
android

利用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中可以按下面的方式实现

建表
  1. postgres=# create table distlock(id int primary key,expired_time interval,owner text,ts timestamptz);
  2. CREATE TABLE
  3. postgres=# insert into distlock(id) values(1);
  4. INSERT 0 1

加锁和续期
  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);
  2. UPDATE 1
获得锁的客户端如果要长时间持有锁必须定期执行相同的方法对锁进行续租,否则会丢锁。

此时,其它客户端取锁会失败
  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);
  2. UPDATE 0

等锁过期后取锁成功
  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);
  2. UPDATE 1

释放锁
  1. postgres=# update distlock set owner=null,ts=now() where id=1 and owner='node2';
  2. UPDATE 1

3. 总结

可以看到用关系数据库实现分布式锁并不复杂。尤其上面基于表实现的锁辅以靠谱的HA部署可以保障锁信息的持久性和不丢失,但用表更新实现锁毕竟比较重,不适合对锁的性能要求非常高的场景。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

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

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

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

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

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

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

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

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

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 Razr 50s shows itself as possible new budget foldable in early leak Motorola Razr 50s shows itself as possible new budget foldable in early leak Sep 07, 2024 am 09:35 AM

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 Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

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

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

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

See all articles