发送消息
import pika
credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('192.168.0.157', 5672, '/', credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
queue_name = 'radarQueue'
channel.queue_declare(queue=queue_name, durable=True, passive=True)
crawled_data = {'key': 'value00'}
crawled_data_json = json.dumps(crawled_data)
channel.basic_publish(exchange='',
routing_key=queue_name,
body=crawled_data_json.encode("utf-8"),
properties=pika.BasicProperties(
delivery_mode=2,
))
print(crawled_data)
connection.close()
接收消息
import pika
credentials = pika.PlainCredentials('username', 'password')
parameters = pika.ConnectionParameters('192.168.0.157', 5672, '/', credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
queue_name = 'radarQueue'
channel.queue_declare(queue=queue_name, durable=True, passive=True)
def callback(ch, method, properties, body):
print(f" [x] Received {body}")
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
try:
channel.start_consuming()
except KeyboardInterrupt:
channel.stop_consuming()
connection.close()