栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

rabbitmq 的 hello world (python)

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 的值一致,要不然消息加不到队列中。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/701543.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号