rabbitmq python 脚本测试

环境: centos7.6,python2.7,rabbitmq docker image: rabbitmq:3.8.9-management,服务器 ip 192.168.1.3

1、使用 docker 部署 rabbitmq,这里做测试,直接使用 --rm 参数,生产需要配置好挂载目录、文件等

docker run -dit --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.8.9-management

2、firewalld 开启端口 5672 和 15672。然后可以通过浏览器浏览 192.168.1.3:15672,查看 rabbitmq 的一些信息。

3、修改 rabbitmq 密码,默认为 guest/guest,这里修改 guest 密码为 admin123

[root@ansible002 ~]# docker exec -it rabbitmq bash
root@c0cda5aaea5d:/# rabbitmqctl list_queues
Timeout: 60.0 seconds ...
Listing queues for vhost / ...
root@c0cda5aaea5d:/# rabbitmqctl change_password guest admin123
Changing password for user "guest" ..

4、生产者脚本 send.py

[root@k8s01 ~]# cat send.py 
#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='192.168.1.3', credentials=pika.PlainCredentials('guest','admin123'), port='5672'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

5、消费者脚本

[root@k8s01 ~]# cat receive.py 
#!/usr/bin/env python
import pika, sys, os

def main():
    connection = pika.BlockingConnection(
      pika.ConnectionParameters(host='192.168.1.3', credentials=pika.PlainCredentials('guest','admin123'), port='5672'))

    channel = connection.channel()

    channel.queue_declare(queue='hello')

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

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

    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

6、pip 安装 pika,执行 python 脚本,浏览器浏览 192.168.1.3:15672 查看变化

pip install pika
python send.py 
python receive.py

参考文章:
https://registry.hub.docker.com/_/rabbitmq/?tab=description
https://www.rabbitmq.com/tutorials/tutorial-one-python.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值