V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
myyou
V2EX  ›  Python

uwsgi 多进程会不会使数据库出现重复数据?

  •  
  •   myyou · 2016-07-26 19:22:23 +08:00 · 4883 次点击
    这是一个创建于 2839 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用 uwsgi 起多进程每个进程是单线程会不会使数据库出现重复数据?如果不会的话,每个进程是多线程时会不会使数据库出现重复数据?麻烦说一下原因。

    9 条回复    2016-08-10 14:43:44 +08:00
    loading
        1
    loading  
       2016-07-26 19:35:57 +08:00 via Android
    关键字:数据库锁机制
    myyou
        2
    myyou  
    OP
       2016-07-26 19:41:16 +08:00
    @loading 假设来自两个进程的重复数据,一条数据插入数据库后,另一条数据等待数据库解锁后不是也可以继续插入吗?
    loading
        3
    loading  
       2016-07-26 19:41:28 +08:00 via Android
    重复数据无论是否多线程都会出现的,很多都要程序配合数据库锁处理,例如注册时检查是否已存在用户名就是你说的问题啦。
    loading
        4
    loading  
       2016-07-26 19:43:10 +08:00 via Android
    如果无法实时处理,很多场景都会设置定时任务,进行数据库的自动程序化维护。
    loading
        5
    loading  
       2016-07-26 19:46:25 +08:00 via Android
    设计表时,可以加入其他列,例如进行提交的用户名,和插入时间,其中这个时间使用 sql 函数,这样你就能做到数据都不同了,便于后面自动去重。

    还有自增 id 等方式
    ryd994
        6
    ryd994  
       2016-07-26 20:48:41 +08:00
    @myyou unique 索引,或者用锁:
    加锁
    检查有没有重复项
    写入
    取锁

    其他进程在检查和写入之间不可能插队
    ziXiong
        7
    ziXiong  
       2016-07-26 21:55:53 +08:00
    重复数据与 uwsgi 是多进程模式还是多线程模式都没有关系。 uwsgi 多进程相当于把 http 负载到了不同的 worker 。
    重复数据是在编程时通过代码检查和数据库加锁,唯一索引等限制的。
    izoabr
        8
    izoabr  
       2016-07-26 22:04:58 +08:00
    事务、锁
    Carrycat
        9
    Carrycat  
       2016-08-10 14:43:44 +08:00
    会的 最简单的体验方法就是 在 gunicorn or wsgi 的 multi workers 情况下连续 POST or Put 相同的 api 就发现了。原因是 django default 是 autocommit=true
    你必须在关键写入地方使用

    with transaction.atomic(): # django >= 1.9
    #or install django-transaction-hooks if django < 1.9 这个插件可以 lock table row not whole table
    https://github.com/carljm/django-transaction-hooks
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2556 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:58 · PVG 16:58 · LAX 01:58 · JFK 04:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.