网站首页 > 资源文章 正文
解决的问题
分布式环境下,希望把用户的操作从并发执行变成原子执行案例:
将订单并发变成串行执行, 相比悲观锁来说能够减少数据库的压力。
原理
redis是单线程的,并发过来的请求,redis都会让他们排队串行执行,redis内部是线程安全的
实现的代码
考虑到如果下单出现异常则锁将永远无法释放,因此做异常捕获,无论代码是否异常要释放锁
考虑到如果下单过程中服务器宕机,则锁将永远无法释放
方案一:应用开始起置空redis中的lock
方案二:给锁设置过期时间,但是如果用户的下单操作超过了lock的过期时间,则下单没有完成锁就失效了。 过期时间设置的太长宕机立刻重启问题也解决不了
# 解决方案 启动一个子线程,每过2s给锁重设过期时间,主线程执行结束,则销毁子线程
销毁线程的代码
from threading import Thread
import inspect
import ctypes
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
def a():
while True:
print("123456789")
if __name__ == '__main__':
t = Thread(target=a)
t.start()
stop_thread(t)
学习资源:
猜你喜欢
- 2024-10-17 python 线程安全(python线程安全的字典)
- 2024-10-17 Python实现订单超时自动取消(python自动发货)
- 2024-10-17 Python基础语法知识,3天熟悉你就牛了
- 2024-10-17 「黑马程序员」「成都校区」Python是如何进行内存管理
- 2024-10-17 Python教程:各商品种类的网购替代率如何计算?
- 2024-10-17 python 并发模块介绍(python的并发)
- 2024-10-17 「学习交流」 「成都地区」Python字典底层实现原理
- 2024-10-17 阿里云PYTHON SDK的使用(阿里云服务器跑python)
- 2024-10-17 罗永浩看了都想学!Python的排序算法核心逻辑大揭秘
- 2024-10-17 Python教程:global和nonlocal关键字用法
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- 电脑显示器花屏 (79)
- 403 forbidden (65)
- linux怎么查看系统版本 (54)
- 补码运算 (63)
- 缓存服务器 (61)
- 定时重启 (59)
- plsql developer (73)
- 对话框打开时命令无法执行 (61)
- excel数据透视表 (72)
- oracle认证 (56)
- 网页不能复制 (84)
- photoshop外挂滤镜 (58)
- 网页无法复制粘贴 (55)
- vmware workstation 7 1 3 (78)
- jdk 64位下载 (65)
- phpstudy 2013 (66)
- 卡通形象生成 (55)
- psd模板免费下载 (67)
- shift (58)
- localhost打不开 (58)
- 检测代理服务器设置 (55)
- frequency (66)
- indesign教程 (55)
- 运行命令大全 (61)
- ping exe (64)
本文暂时没有评论,来添加一个吧(●'◡'●)