Celery + Eventlet + 非阻塞请求
Celery + Eventlet + non blocking requests
我在 celery workers
中使用 Python requests
进行大量(~10/秒)API 调用(包括 GET,POST、放置、删除)。每个请求大约需要 5-10 秒才能完成。
我在 eventlet
池中尝试了 运行 个 celery worker,并发数为 1000。
因为 requests
是阻塞进程,每个并发连接都在等待一个请求。
如何使 requests
异步?
来自 docs:
there are lots of projects out there that combine Requests with one of
Python’s asynchronicity frameworks. Two excellent examples are
grequests and requests-futures.
对于 eventlet,您可以使用 erequests。
使用 eventlet monkey patching 使任何纯 python 库成为非阻塞。
补丁单库
# import requests # instead do this:
import eventlet
requests = eventlet.import_patched('requests')
修补一切
import eventlet
eventlet.monkey_patch() # must execute as early as possible
...
# everything is non-blocking now:
import requests, amqp, memcache, paramiko, redis
更新:有known issue 猴子补丁请求库。如果你得到:
ImportError: cannot import name utils
,然后将导入行修改为
requests = eventlet.import_patched('requests.__init__')
我在 celery workers
中使用 Python requests
进行大量(~10/秒)API 调用(包括 GET,POST、放置、删除)。每个请求大约需要 5-10 秒才能完成。
我在 eventlet
池中尝试了 运行 个 celery worker,并发数为 1000。
因为 requests
是阻塞进程,每个并发连接都在等待一个请求。
如何使 requests
异步?
来自 docs:
there are lots of projects out there that combine Requests with one of Python’s asynchronicity frameworks. Two excellent examples are grequests and requests-futures.
对于 eventlet,您可以使用 erequests。
使用 eventlet monkey patching 使任何纯 python 库成为非阻塞。
补丁单库
# import requests # instead do this: import eventlet requests = eventlet.import_patched('requests')
修补一切
import eventlet eventlet.monkey_patch() # must execute as early as possible ... # everything is non-blocking now: import requests, amqp, memcache, paramiko, redis
更新:有known issue 猴子补丁请求库。如果你得到:
ImportError: cannot import name utils
,然后将导入行修改为
requests = eventlet.import_patched('requests.__init__')