import pika
# 仅为记录 慎用
# 一个或多个connection
# 一个线程一个channel 或多个channel(注意线程安全)
# 一个exchange占用一个connection
# 一个 channel.start_consuming() 占用一个connection
# 先起消费者再起生产者,不然堆积的消息会无序
def sendmessage(channel,route='',routetype='queue',routekey='',body='',delivery_mode=False,uuid = None,reply_to=None):
if routetype in ['topic','direct','fanout']:
channel.exchange_declare(exchange=str(route), exchange_type=routetype)
if routetype == 'fanout':
channel.basic_publish(exchange=str(route), routing_key='', body=str(body), )
else:
channel.basic_publish(exchange=str(route), routing_key=str(routekey), body=str(body),)
elif routetype == 'queue':
if delivery_mode == True:
channel.basic_publish(exchange='', routing_key=str(route),body=str(body),properties=pika.BasicProperties(
delivery_mode=2,
correlation_id=str(uuid) if uuid is not None else None,
reply_to=str(reply_to) if reply_to is not None else None ))
else:
channel.basic_publish(exchange='', routing_key=str(route), body=str(body), properties=pika.BasicProperties(
correlation_id=str(uuid) if uuid is not None else None,
reply_to=str(reply_to) if reply_to is not None else None))
else:
print("RabbitMQ routetype is in ['topic','direct','fanout', 'queue']")
return -1
def recivemessage_from_Q_2_func(connection,channel,route='',func=None,auto_ack=True,block=False):
def callback(ch, method, properties, body):
try:
if func!=None:
func(str(body, encoding = "utf-8"),str(properties.correlation_id),str(properties.reply_to))
else:
print('body: ',str(body, encoding = "utf-8"),'uuid: ',properties.correlation_id,'reply_to: ',properties.reply_to)
finally:
if auto_ack ==False:
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue=str(route), on_message_callback=callback,auto_ack=auto_ack )
if block ==False:
connection.process_data_events()
else:
channel.start_consuming()
def recivemessage_from_exchange_2_func(channel=None,route='',routetype='fanout',routekey=['#',],func=None):
if routetype in ['topic', 'direct', 'fanout']:
channel.exchange_declare(exchange=str(route), exchange_type=routetype)
result = channel.queue_declare(queue='',exclusive=True )
queue_name = result.method.queue
if routetype=='fanout':
channel.queue_bind(exchange=str(route), queue=queue_name)
else:
if type(routekey) is not list:
raise TypeError
for key in routekey:
if type(key) is not str:
raise TypeError
for key in routekey:
channel.queue_bind(exchange=str(route), queue=queue_name,routing_key=key)
def callback(ch, method, properties, body):
if func != None:
func(str(body, encoding = "utf-8"))
else:
print('body: ',str(body, encoding = "utf-8"))
channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True)
channel.start_consuming()
else:
print("RabbitMQ routetype is in ['topic','direct','fanout']")
return -1
python rabbit MQ代码记录
最新推荐文章于 2024-04-06 16:49:45 发布