通过python代码理解rabbitmq消息收发原理

本文介绍如何使用Python来模拟RabbitMQ的消息发送与接收过程,包括环境配置、用户与权限设置以及具体代码实现。

作者:吴业亮
博客:http://blog.youkuaiyun.com/wylfengyujiancheng

一、通过python模拟收发消息

这里写图片描述
1、在各个节点上安装epel源

# yum install  epel*  -y

2、安装python库

# yum --enablerepo=epel -y install python2-pika

3、在rabbitmq-server节点上
1)、创建用户

# rabbitmqctl add_user wuyeliang password 

2)、创建虚拟主机

# rabbitmqctl add_vhost /my_vhost

3)、赋予权限

# rabbitmqctl set_permissions -p /my_vhost wuyeliang ".*" ".*" ".*" 

4、在rabbitmq节点上模拟发消息,代码如下

# vi send_msg.py
#!/usr/bin/env python
import pika
credentials = pika.PlainCredentials('wuyeliang', 'password') #注意用户名及密码
connection = pika.BlockingConnection(pika.ConnectionParameters(
                                     'localhost',
                                     5672,
                                     '/my_vhost',
                                     credentials))
channel = connection.channel()
channel.queue_declare(queue='Hello_World')
channel.basic_publish(exchange='',
                      routing_key='Hello_World',
                      body='Hello RabbitMQ World!')
print(" [x] Sent 'Hello_World'")
connection.close()

这里写图片描述

4、在client节点上模拟收消息,代码如下

# vi receive_msg.py
 #!/usr/bin/env python
import signal
import pika
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)
credentials = pika.PlainCredentials('wuyeliang', 'password')
connection = pika.BlockingConnection(pika.ConnectionParameters(
                                     'dlp.srv.world',
                                     5672,
                                     '/my_vhost',
                                     credentials))
channel = connection.channel()
channel.queue_declare(queue='Hello_World')
def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)
channel.basic_consume(callback,
                      queue='Hello_World',
                      no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值