Skip to main content
 首页 » 编程设计

python之rabbitMQ消息的存储方式

2025年04月02日27emanlee

我正在使用带有 python 的 RabbitMQ 服务器向服务器发送和接收消息 这是我用来向代码发送消息的代码。

import numpy as np 
import pandas as pd 
import pika 
 
connection = pika.BlockingConnection(pika.ConnectionParameters( 
             host='localhost')) 
channel = connection.channel() 
channel.queue_declare(queue='Q1') 
message = 'Hello World' 
channel.basic_publish(exchange='', 
                      routing_key='Q1', 
                      body=message) 
# Printing the Sending Confirmation of ID 
print(" [x] Sent %r" % message) 
 
connection.close() 

输出:

[x] Sent 'Hello World'  

这是我用来从队列接收消息的代码

import pika 
import sys 
 
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) 
channel = connection.channel() 
channel.queue_declare(queue='Q1') 
def callback(ch, method, properties, body): 
    print(" [x] Received %r" % body) 
 
channel.basic_consume(callback, queue='Q1', no_ack=True) 
channel.start_consuming() 

输出:

[x] Received 'Hello World' 

问题是我想将此消息(即“Hello World”)保存到一个变量中,然后在我的程序中使用它

但是我无法保存消息。

如何将它保存到变量中。 Multiple Messages in the queue 的解决方案是什么

请您参考如下方法:

The problem is I want to save this message i.e. "Hello World" to a variable and then use it in my program

您已经有了一个可以在程序中使用的变量 - body。如果您想将基础架构代码(即RabbitMq/pika)与业务逻辑分离,那么您只需声明另一个函数并传递body 到它。

def processing_function(message_received): 
    print(" [x] Received %r" % message_received) 
 
def callback(ch, method, properties, body): 
    processing_function(body) 

想法是,一旦收到消息,pika 就会调用callback,然后将body 传递给执行计算的processing_function。

如果您难以理解回调函数,我建议您阅读 this首先。