rabbitmq 使用带有 pika 的线程 [英] rabbitmq using threads with pika

查看:72
本文介绍了rabbitmq 使用带有 pika 的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用rabbitmq 获得一个基本的队列系统,但是当我尝试使用线程时,它似乎只运行了 1 个线程.

I'm trying to get a basic queue system with rabbitmq, but when I try to use threads, it only seems to run 1 thread.

我的代码:

import pika
import threading

rabbit_url = "amqp://user:pass!@127.0.0.1:5672/%2f"

def start(max_threads):
    for i in xrange(max_threads):
        t = threading.Thread(target=run)
        t.start()
        t.join()

def run():
    connection = pika.BlockingConnection(pika.URLParameters(rabbit_url))
    channel = connection.channel()
    channel.basic_consume(callback,
                          queue='docketq',
                          no_ack=True)

    channel.start_consuming()

def callback(ch, method, properties, body):
    do_work(body)

def do_work(body):
    print body

推荐答案

t.join() 等待线程完成.在 start() 循环的第一次迭代中,您启动第一个线程,然后等待它完成,但它永远不会因为 channel.start_sumption() 是一个无限循环等待传入消息.

t.join() waits for the thread to finish. In the first iteration of the loop in start() you start the first thread and then wait for it to finish, but it never will because channel.start_consuming() is an infinite loop waiting for incoming messages.

这篇关于rabbitmq 使用带有 pika 的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆