【RabbitMQ】【Python】 Hello World

本文介绍如何使用Python与RabbitMQ结合来发送和接收消息。通过具体的代码示例,演示了如何创建连接、声明队列、发送消息及接收消息的基本流程。适用于初学者快速上手RabbitMQ消息队列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hello World by RabbitMQ in Python

环境

Today: 2019/04/02

Ubuntu – 18.04

RabbitMQ – 3.6.10

apt install erlang erlang-nox
apt install rabbitmq-server --fix-missing
sudo rabbitmqctl status

Python – 3.6.7

pika – 1.0.0

pip install --user pika

Hello World

https://www.rabbitmq.com/tutorials/tutorial-one-python.html

send

#!/usr/bin/env python3
import sys
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

try:
    msg = sys.argv[1]
except:
    msg = "Hello World!"

channel.basic_publish(
    exchange='',
    routing_key='hello',
    body=msg)

print(" [x] Sent '{}'".format(msg))
connection.close()

receive

#!/usr/bin/env python3
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')


def callback(ch, method, properties, body):
    body = body.decode()
    if body == "quit":
        ch.basic_cancel(consumer_tag='hello')
        ch.stop_consuming()
    else:
        print(" [x] Received %r" % body)


channel.basic_consume(
    queue='hello', on_message_callback=callback, auto_ack=True)

print(' [*] Waiting for messages......')
print('\tTo exit press CTRL+C, or send "quit" message')
channel.start_consuming()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值