python使用rabbitmq阻塞_RabbitMQ非阻塞连接

表格FAQ: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,

所以让我们在线程内部创建连接:import pika

class PikaMassenger():

exchange_name = '...'

def __init__(self, *args, **kwargs):

self.conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

self.channel = self.conn.channel()

self.channel.exchange_declare(

exchange=self.exchange_name,

exchange_type='topic')

def consume(self, keys, callback):

result = self.channel.queue_declare('', exclusive=True)

queue_name = result.method.queue

for key in keys:

self.channel.queue_bind(

exchange=self.exchange_name,

queue=queue_name,

routing_key=key)

self.channel.basic_consume(

queue=queue_name,

on_message_callback=callback,

auto_ack=True)

self.channel.start_consuming()

def __enter__(self):

return self

def __exit__(self, exc_type, exc_value, traceback):

self.conn.close()

def start_consumer():

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

print(" [x] %r:%r consumed" % (method.routing_key, body))

with PikaMassenger() as consumer:

consumer.consume(keys=[...], callback=callback)

consumer_thread = threading.Thread(target=start_consumer)

consumer_thread.start()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值