当前位置:网站首页>分布式锁介绍
分布式锁介绍
2022-06-12 03:59:00 【UPythonFish】
分布式锁介绍
分布式锁: 在分布式的环境中加锁,通俗点就是在集群环境下加锁
用途: 用在抢购,预售等用途,用来保证多台机器上的数据并发安全

mysql中的悲观锁,乐观锁就是分布式锁的一种,但是mysql的性能很低,在高并发的环境下,一般不用mysql的锁,而使用其他的分布式锁。
使用可以基于redis实现,并且非常简单,官方提供了Redlock模块调用,
from redlock import RedLock
lock = RedLock('distribted_lock')
lock.acquire() # 获取锁
# 抢到锁之后的逻辑
do_something()
lock.release() # 释放锁
内部逻辑
使用命令介绍
(1)SETNX
SETNX key val:当且仅当key不存在时,set一个key为val的字符串,返回1;若key存在,则什么都不做,返回0。
(2)expire
expire key timeout:为key设置一个超时时间,单位为second,超过这个时间锁会自动释放,避免死锁。
(3)delete
delete key:删除key
在使用Redis实现分布式锁的时候,主要就会使用到这三个命令。实现思想
(1)获取锁的时候,使用setnx加锁,并使用expire命令为锁添加一个超时时间,超过该时间则自动释放锁,锁的value值为一个随机生成的UUID,通过此在释放锁的时候进行判断。
(2)获取锁的时候还设置一个获取的超时时间,若超过这个时间则放弃获取锁。
(3)释放锁的时候,通过UUID判断是不是该锁,若是该锁,则执行delete进行锁释放。
demo
# 连接redis
redis_client = redis.Redis(host="localhost",
port=6379,
password=password,
db=10)
# 获取一个锁
#lock_name:锁定名称
# acquire_time: 客户端等待获取锁的时间
# time_out: 锁的超时时间
def acquire_lock(lock_name, acquire_time=10, time_out=10):
"""获取一个分布式锁"""
identifier = str(uuid.uuid4())
end = time.time() + acquire_time
lock = "string:lock:" + lock_name
while time.time() < end:
if redis_client.setnx(lock, identifier):
# 给锁设置超时时间, 防止进程崩溃导致其他进程无法获取锁
redis_client.expire(lock, time_out)
return identifier
elif not redis_client.ttl(lock):
redis_client.expire(lock, time_out)
time.sleep(0.001)
return False
#释放一个锁
def release_lock(lock_name, identifier):
"""通用的锁释放函数"""
lock = "string:lock:" + lock_name
pip = redis_client.pipeline(True)
while True:
try:
pip.watch(lock)
lock_value = redis_client.get(lock)
if not lock_value:
return True
if lock_value.decode() == identifier:
pip.multi()
pip.delete(lock)
pip.execute()
return True
pip.unwatch()
break
except redis.excetions.WacthcError:
pass
return False
补充
分布式id的选择
- 选择mysql的自增类型,性能不高
- 使用当前时间戳,多台机器,同一个时刻,id会重复
- 使用uuid,数据量大,也可能会重复
- 多台服务器生成不重复id: 推荐使用雪花算法,并且python有现成的模块可以实现
分布式锁还可以通过ZooKeeper实现
边栏推荐
- Notes relatives à l'application du certificat de l'AC et de la paire de clés
- [FPGA chaos] implementation of FPGA based chaotic system Verilog
- In 2022, don't you know the difference between arrow function and ordinary function?
- LINQ group by and select series - LINQ group by and select collection
- Page crash handling method
- 数据库新建表,以前没问题的,今天
- [fpga+gps receiver] detailed design introduction of dual frequency GPS receiver based on FPGA
- PostgreSQL basic introduction and deployment
- [C language] encapsulation interface (addition, subtraction, multiplication and division)
- Implementation of fitness club management system based on SSH
猜你喜欢

云原生概述

mysql/oracle 以唯一时间为分界,小于等于该时间求和,大于该时间求和

Convert py file to EXE file

成功解决:WARNING: There was an error checking the latest version of pip.

Smart Panel wifi Linkage Technology, esp32 wireless chip module, Internet of Things WiFi Communication Application

Paper recommendation: relicv2, can the new self supervised learning surpass supervised learning on RESNET?

根据变换矩阵进行图像拼接

顺序表与链表-----进阶

Emperor Wu of Wei knew that he could not correct it, so he stopped offering his words

无线物联网WiFi模块方案,ESP32-S3芯片技术,助力设备智能化
随机推荐
根据变换矩阵进行图像拼接
JSP实现银柜台业务绩效考核系统
[fpga+fft] design and implementation of FFT frequency meter based on FPGA
Sequence list and linked list ----- advanced
Pat class B 1067 trial password (20 points)
【C语言】变量本质分析
Summary of sequential, modulelist, and moduledict usage in pytorch
认真工作对自己到底意味着什么?
[mysql][mysql 8.0 compressed package installation method]
Simple database connection example
Solution to missing in unity script
後續版本是否會支持代碼塊搜索高亮顯示
(idea)the file size(2.85M) exceeds configured limit(2.56M).Code insight features are not available问题
调用提醒事项
Evolution and practice of Unicom real-time computing platform
Object detection model rfbnet -- a very useful model
R语言使用survival包的coxph函数构建cox回归模型、使用ggrisk包的ggrisk函数可视化Cox回归的风险评分图(风险得分图)、并解读风险评分图、基于LIRI数据集(基因数据集)
Successfully solved: warning: there was an error checking the latest version of pip
CA证书及密钥对应用笔记
Review of technical economy and Enterprise Management Chapter 4