您现在的位置是:主页 > Web前端技术 > Web前端技术

RabbitMQ发送端接收端生产者消费者的示例分析编程语言

IDCBT2021-12-24服务器技术人已围观

简介这篇文章给大家分享的是有关RabbitMQ发送端接收端生产者消费者的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。 rabbit_conn_send_producer.py im

这篇文章给大家分享的是有关RabbitMQ发送端接收端生产者消费者的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

rabbit_conn_send_producer.py
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
    'localhost'))#rabbit默认端口5672 建立一个基本的 socket连接
channel = connection.channel()#声明一个管道 在管道里面发消息

# 声明queue
channel.queue_declare(queue='hello')

# n 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='Hello World!') #body 发送的消息
print(" [x] Sent 'Hello World!'")
connection.close()

rabbit_conn_recive_consumer.py
# _*_coding:utf-8_*_
__author__ = 'Alex Li'
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
    'localhost')) #rabbit默认端口5672 建立一个基本的 socket连接
channel = connection.channel()#声明一个管道 在管道里面收消息

# You may ask why we declare the queue again ‒ we have already declared it in our previous code.
# We could avoid that if we were sure that the queue already exists. For example if send.py program
# was run before. But we're not yet sure which program to run first. In such cases it's a good
# practice to repeat declaring the queue in both programs.
#channel.queue_declare(queue='hello')#声明queue


def callback(ch, method, properties, body):#处理消息
    print("---->",ch,method,properties)#ch 管道内存对象地址 method:发给queue的信息
    print(" [x] Received %r" % body)


channel.basic_consume(#消费消息
           callback,#如果收到消息,就调用CALLBACK函数来处理消息
           queue='hello',#从哪个队列里收消息
           

标签:

很赞哦! ()