#发送者:import pika
# 建立一个实例
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost',5672) # 默认端口5672,可不写
)
# 声明一个管道,在管道里发消息
channel = connection.channel()
# 在管道里声明queue
channel.queue_declare(queue='hello',durable=True)
classProducerMQ(object):def__init__(self):passdef__enter__(self):return self
def__exit__(self, exc_type, exc_val, exc_tb):ifnot connection.is_closed:
connection.close()
defsend(self,body):# RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',
routing_key='hello', # queue名字
body=body,# 消息内容
properties=pika.BasicProperties(
delivery_mode=2# 消息持久化,在rabbitmq重启后队列及消息依然存在
)
)
print(" [x] Sent {}".format(body))
if __name__ == '__main__':
with ProducerMQ() as producer:
[producer.send('hello {}'.format(i)) for i in range(10)]
#消费者:import pika
# 建立一个实例
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost',5672) # 默认端口5672,可不写
)
# 声明一个管道,在管道里发消息
channel = connection.channel()
# 在管道里声明queue
channel.queue_declare(queue='hello',durable=True)
classConsumerMQ(object):def__init__(self):
self.count=0def__enter__(self):return self
def__exit__(self, exc_type, exc_val, exc_tb):ifnot connection.is_closed:
connection.close()
defcallback(self,ch, method, properties, body):if self.count>=5: #消费掉5个后退出
connection.close()
return
print(" [x] Received %r{} {}" .format(self.count,body))
ch.basic_ack(delivery_tag=method.delivery_tag)
self.count+=1defreceive(self):# RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_consume(self.callback, queue='hello')
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
if __name__ == '__main__':
with ConsumerMQ() as consumer:
consumer.receive()
代码2
import pika
import time
import string
import json
host = '*.*.*.*'
username = '*'# 指定远程rabbitmq的用户名
pwd = '*'# 密码
queue_name = 'test'# 队列名
user_pwd = pika.PlainCredentials(username, pwd)
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=host, port=5672,
credentials=user_pwd)) # 创建连接
channel = connection.channel() # 连接上创建一个频道# durable 表示是否持久化,# exclusive是否排他,如果为True则只允许创建这个队列的消费者使用,# auto_delete 表示消费完是否删除队列
channel.queue_declare(queue=queue_name, durable=True, exclusive=False,
auto_delete=False) # 声明一个队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另一方能正常运行# 生产者,发送消息defsend_message(data):# 需要将字典dumps成字符串
channel.basic_publish(exchange='', # 交换机
routing_key=queue_name, # 路由键,写明将消息发往哪个队列,本例是将消息发往队列queue_name
body=json.dumps(data), # 生产者要发送的消息
properties=pika.BasicProperties(
delivery_mode=2, ) # 设置消息持久化,将要发送的消息的属性标记为2,表示该消息要持久化)
)
# 消费者,接收消息defreceive_message():# prefetch_count设置为3,表示每次最多只取三个消息
channel.basic_qos(prefetch_count=3)
channel.basic_consume(callback, queue=queue_name)
print(' [*] Waiting for messages. To exit press CTRL+C')
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.close()
connection.close()
defcallback(ch, method, properties, body):
result = handle_data(body)
if result == 1:
print(" [消费者] Done")
ch.basic_ack(delivery_tag=method.delivery_tag) # 接收到消息后会给rabbitmq发送一个确认else:
print(" [x] handle data error")
ch.basic_reject(delivery_tag=method.delivery_tag)
# 代写接口,处理下一步的数据defhandle_data(body):try:
data = json.loads(body)
print(" [消费者] Received {}".format(data))
time.sleep(10)
except:
return0else:
return1if __name__ == '__main__':
# send为True调用生产者,send为False调用消费者
send = True# 发送数据if send:
message = [{k: v} for k, v in enumerate(string.ascii_lowercase)]
for m in message:
print(m)
send_message(data=m)
# 接受数据else:
receive_message()