Pika是用于Python的RabbitMQ(AMQP-0-9-1)客户端库,官方文档地址:https://pypi.org/project/pika/
工作模式:其中P表示produce,生产者的意思,也可以称为发送者,实例中表现为send.py;C表示consumer,消费者的意思,也可以称为接收者,实例中表现为receive.py;中间红色的表示队列的意思,实例中表现为hello队列。
1 import pika 2 3 4 credentials = pika.PlainCredentials('admin', 'passwd') 5 connection = pika.BlockingConnection(pika.ConnectionParameters( 6 'ip',credentials=credentials)) 7 8 9 10 channel = connection.channel() #建立了rabbit 协议的通道 11 12 # 声明queue, 13 channel.queue_declare(queue='hello') 14 15 # n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange. 16 channel.basic_publish(exchange='', 17 routing_key='hello', 18 body='Hello World!') 19 ''' 20 exchange表示交换器,能精确指定消息应该发送到哪个队列 21 routing_key设置为队列的名称 22 body就是发送的内容 23 ''' 24 print(" [x] Sent 'Hello World!'") 25 connection.close()
可以使用
rabbitmqctl list_queues命令查看队列
1 import pika 2 import time 3 4 credentials = pika.PlainCredentials('admin', 'passwd') 5 connection = pika.BlockingConnection(pika.ConnectionParameters( 6 'ip',credentials=credentials)) 7 8 channel = connection.channel() 9 10 channel.queue_declare(queue='hello') 11 12 13 def callback(ch, method, properties, body): 14 15 print("received msg...start processing....",body) 16 time.sleep(20) 17 print(" [x] msg process done....",body) 18 19 20 channel.basic_consume(callback, 21 queue='hello', 22 no_ack=True) 23 24 print(' [*] Waiting for messages. To exit press CTRL+C') 25 channel.start_consuming()