rabbitmq 的 hello world (python)
2022/1/10 1:08:20
本文主要是介绍rabbitmq 的 hello world (python),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
rabbitmq 的hello_world,最见简单的模式。
- 生产者
代码如下
import pika class Producer(object): def __init__(self, queue_name, username, password, host, port,virtual_host): con_param = { "host": host, "port": port, "virtual_host": virtual_host, "credentials": pika.credentials.PlainCredentials( username, password) } # 建立连接 self.con = pika.BlockingConnection(pika.ConnectionParameters(**con_param)) # 创建通道 self.channel = self.con.channel() # 声明队列 self.channel.queue_declare(queue=queue_name) def send_message(self, routing_key, body): # 发送消息 self.channel.basic_publish(exchange="", routing_key=routing_key, body=body) # 关闭通道 self.channel.close() # 关闭连接 self.con.close() if __name__ == '__main__': p = Producer("test","tom","tom@tom","localhost",5672,"/afei") p.send_message("test","hello world!")
- 消费者
import pika class Consumer(object): def __init__(self, queue_name, username, password, host, port, virtual_host): con_param = { "host": host, "port": port, "virtual_host": virtual_host, "credentials": pika.credentials.PlainCredentials( username, password) } # 建立连接 self.con = pika.BlockingConnection(pika.ConnectionParameters(**con_param)) # 创建通道 self.channel = self.con.channel() # 声明队列 self.channel.queue_declare(queue=queue_name) def consume_message(self, queue_name): def callback(ch, method, properties, body): print("ch===%r" % ch) print("method===%r" % method) print("properties===%r" % properties) print("[x] Received %r" % body) # 消费对象 self.channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True) # 开始消费 self.channel.start_consuming() if __name__ == '__main__': try: c = Consumer("test", "tom", "tom@tom", "localhost", 5672, "/afei") c.consume_message("test") except KeyboardInterrupt: exit(0)
注意:
生产者的
队列名一定要和routing_key 的值一致,要不然消息加不到队列中。
这篇关于rabbitmq 的 hello world (python)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型
- 2024-12-23使用python部署一个usdt合约,部署自己的usdt稳定币
- 2024-12-20Python编程入门指南