简体   繁体   中英

rabbitmq using threads with pika

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.

my code:

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() 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.

Pika is not threadsafe. From the Pika FAQ :

Is Pika thread safe?

Pika does not have any notion of threading in the code. If you want to use Pika with threading, make sure you have a Pika connection per thread, created in that thread. It is not safe to share one Pika connection across threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM