CELERY_ROUTES - 如何根据任务名称进行路由
我试图让 celery 根据任务名称路由任务...基本上,我有名为“worker.some_name”和“web.some_name”的任务,并且我使用两个不同的队列,称为worker和分别是网络。我希望所有工作任务都进入工作队列,反之亦然。目前我有一个像这样的大 CELERY_ROUTES 字典:
CELERY_ROUTES = {
"web.some_name": {
"queue": "web"
},
"web.some_other_name": {
"queue": "web"
},
etc.... }
但我想要更通用的东西,例如:
CELERY_ROUTES = (MyRouter(), )
class MyRouter(object):
def route_for_task(self, task, args=None, kwargs=None):
if task.split('.')[0] == "worker":
return {"queue": "worker"}
return {"queue": "web"}
但这似乎不起作用。有什么想法吗?谢谢。
I'm trying to get celery to route tasks based on the name of the task... basically, I have tasks that are name 'worker.some_name' and 'web.some_name', and I use two different queues, called worker and web respectively. I would like all worker tasks to go to the worker queue and vice-versa. Currently I have a big CELERY_ROUTES dictionary like this:
CELERY_ROUTES = {
"web.some_name": {
"queue": "web"
},
"web.some_other_name": {
"queue": "web"
},
etc.... }
But I would like something more generic like:
CELERY_ROUTES = (MyRouter(), )
class MyRouter(object):
def route_for_task(self, task, args=None, kwargs=None):
if task.split('.')[0] == "worker":
return {"queue": "worker"}
return {"queue": "web"}
But this doesn't seem to work. Any ideas? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须对 py 文件中定义的任务使用装饰器“@app.task”。
您可以使用 @app.task(queue='queue_name') 路由您的任务
You must have used the decorator "@app.task" for the task you've defined in py file.
You can route your task using @app.task(queue='queue_name')
您应该能够通过将交换类型从直接更改为主题来完成您想要的操作。通过这种方式,您可以将任务指定为 web.* 或 worker.*
您可以在此处阅读:http://ask.github.com/celery/userguide/routing.html#topic-exchanges
You should be able to do what you want by changing the exchange type from direct to topic. This way you can specify the tasks as web.* or worker.*
You can read up on it here: http://ask.github.com/celery/userguide/routing.html#topic-exchanges
Celery 3.x 默认不支持通配符路由,但你可以自己实现。
这是一个复制粘贴解决方案:
用法:
TaskRouter 的工作原理:
Wildcard routing is not supported in Celery 3.x by default, but you can implement it yourself.
Here is a copy-paste solution:
Usage:
How the TaskRouter works: