推荐学习书目
› 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
cevincheung
V2EX  ›  Python

Python 怎么优雅的做个 queue worker

  •  
  •   cevincheung ·
    cevin · Sep 3, 2017 · 3044 views
    This topic created in 3357 days ago, the information mentioned may be changed or developed.

    利用 python 做了个队列消费者(器) 伪代码:

    while True:
        job = beanstalk.watch('test')
        body = job.body
        if (body.type == 'sms'):
            sendsms(body.params,job)
        elif (body.type == 'email'):
            sendemail(body.params,job)
    

    怎么可以更优雅的让他动态 fork 出另外一个线程去执行,而让这个 worker 的主入口继续获取别的队列内容。

    8 replies  •  2017-09-06 19:00:08 +08:00
    Lax
    Lax
    Sep 3, 2017
    1
    while job = beanstalk.watch('test'):
    fork do
    blablabla...

    any way, fork 出来的是进程
    NoAnyLove
    NoAnyLove
    Sep 3, 2017
    2
    concurrent.future

    话说,你到底想要在线程中执行还是进程中执行啊? fork 不是用来创建新进程的吗?
    cevincheung
    cevincheung
    OP
    Sep 4, 2017
    3
    @NoAnyLove #2 描述有点问题,总之目标就是建立一个队列内容获取的东西,一旦获取就赶紧丢给真正执行这个队列的负责 [人] ,然后继续获取其他队列中数据。
    wuhang89
    wuhang89
    Sep 4, 2017
    4
    都用队列了,多开几个进程呗,上层拿一个 supervisor 做个守护进程好了,搞那么麻烦干嘛。
    keakon
    keakon
    Sep 4, 2017
    5
    理论上性能最好的方式是设置 SO_REUSEPORT,每个进程都去监听 beanstalk 的端口即可。不过需要手动改下客户端源码。
    keakon
    keakon
    Sep 4, 2017
    6
    想错了,又不是服务端,SO_REUSEPORT 都不用设置,直接多进程消费即可。
    yylucifer
    yylucifer
    Sep 6, 2017
    8
    我擦,和我以前写过的消息队列居然是一样的,我也用的 beanstalk。。

    这个可以写得很复杂,简单点就做个反射调用就可以了。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1031 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 22:50 · PVG 06:50 · LAX 14:50 · JFK 17:50
    ♥ Do have faith in what you're doing.