基于数据库的分布式锁 代码
时间: 2023-12-14 07:36:39 浏览: 76
以下是基于数据库的分布式锁的示例代码(使用MySQL数据库):
```python
import pymysql
class DistributedLock:
def __init__(self, host, user, password, db, table_name):
self.conn = pymysql.Connect(host=host, user=user, password=password, db=db, charset='utf8mb4')
self.table_name = table_name
def acquire_lock(self, lock_name, timeout=10):
cursor = self.conn.cursor()
cursor.execute('SELECT GET_LOCK(%s, %s)', (lock_name, timeout))
result = cursor.fetchone()[0]
if result == 1:
return True
else:
return False
def release_lock(self, lock_name):
cursor = self.conn.cursor()
cursor.execute('SELECT RELEASE_LOCK(%s)', (lock_name,))
result = cursor.fetchone()[0]
if result == 1:
return True
else:
return False
```
使用示例:
```python
lock = DistributedLock('localhost', 'root', 'password', 'test', 'locks')
if lock.acquire_lock('my_lock'):
# do something
lock.release_lock('my_lock')
else:
print('Failed to acquire lock')
```
在上面的示例代码中,我们使用了MySQL数据库的GET_LOCK和RELEASE_LOCK函数来实现分布式锁。GET_LOCK函数会尝试获取一个名为lock_name的锁,如果该锁已经被其他客户端获取,则会等待timeout秒后再次尝试获取。如果成功获取到锁,则返回1;否则返回0。RELEASE_LOCK函数则会释放一个已经获取到的锁。
阅读全文