rabbitmq客户端pika一个channel消费多个queue

我们知道rabbitmq在一个connection中可以声明多个channel, 一个channel可以供给一个线程来安全的使用, 而一个channel是可以同时从多个队列接收数据的,我们称为消费多个queue, 那么在python客户端pika中, 如果一个channel消费多个queue, 对不同的消费是否可以执行不同的callback呢? 为了验证这个, 写了这么一个测试代码

test_queue_send.py

# -*- coding: utf-8 -*-
from packages.rabbit import tornado_conn
import time
import pika
import uuid

queue_name = 'queue1'

def proc():
    global queue_name
    if queue_name == 'queue1':
        queue_name = 'queue2'
    else:
        queue_name = 'queue1'
    content = str(uuid.uuid4())
    print 'sent to', queue_name, 'content:', content
    tornado_conn.get_channel().basic_publish(
        exchange='',
        routing_key=queue_name,
        properties=pika.BasicProperties(
            content_type='application/octet-stream'
        ),
        body=content
    )
    tor = tornado_conn.TornadoConnection.instance()
    tor.add_timeout(3, proc)
    pass

tor = tornado_conn.TornadoConnection.instance()
tor.add_timeout(5, proc)
tornado_conn.TornadoConnection.start()

test_queue_receive.py

# -*- coding: utf-8 -*-
from packages.rabbit import tornado_conn

def queue_1_receive(ch, metd, props, body):
    print 'queue_1_receive', metd.routing_key, 'received:', body
    pass


def queue_2_receive(ch, metd, props, body):
    print 'queue_2_receive', metd.routing_key, 'received:', body
    pass


def on_queue_1_declared(frame):
    tornado_conn.get_channel().basic_consume(
        queue_1_receive, 
        no_ack=True, 
        queue=frame.method.queue
    )
    pass


def queue_1_declare():
    tornado_conn.get_channel().queue_declare(
        queue='queue1',
        exclusive=True, 
        auto_delete=True,
        callback=on_queue_1_declared
    )
    pass


def on_queue_2_declared(frame):
    tornado_conn.get_channel().basic_consume(
        queue_2_receive, 
        no_ack=True, 
        queue=frame.method.queue
    )
    pass


def queue_2_declare():
    tornado_conn.get_channel().queue_declare(
        queue='queue2',
        exclusive=True, 
        auto_delete=True,
        callback=on_queue_2_declared
    )
    pass


tor = tornado_conn.TornadoConnection.instance()
tor.add_callback(queue_1_declare)
tor.add_callback(queue_2_declare)
tornado_conn.TornadoConnection.start()

然后先运行接收端, 再运行发送端, 结果验证了当一个channel同时消费多个queue时, 不同queue过来的数据可以执行不同的回调, 这样在python客户端中, 每个connection实际只需要开启一个channel就可以满足需求了.

posted on 2013-05-05 21:12  盐味  阅读(2205)  评论(0编辑  收藏  举报