概述今天主要介绍三个python脚本,来模拟操作 rabbitmq,后面实验需要~
一、安装rabbitmqRabbitmq基于erlang,得先安装erlang,erlang的下载地址
1、安装erlang
yum install -y lrzsz wget gcc glibc-devel make ncurses-devel openssl-devel autoconf
2、安装rabbitmq
3、Rabbitmq服务器的管理
启动:rabbitmq-server -detached (systemctl rabbitmq-server start)
关闭:rabbitmqctl stop
状态查看:rabbitmqctl status启用插件:rabbitmq-plugins enable rabbitmq_management添加远程登录的用户:rabbitmqctl add_user hwb fswl@1234 设置用户为管理员:rabbitmqctl set_user_tags hwb administrator
设置远程登录(配置权限、写权限、读权限):rabbitmqctl set_permissions -p "/" hwb ".*" ".*" ".*"
二、安装pika模块(离线安装)--安装setuptools
wget
unzip setuptools-38.5.2.zip
cd setuptools-38.5.2
python setup.py install
--安装pip
wget
tar -xvf pip-18.0.tar.gz
cd pip-18.0
python setup.py build && python setup.py install
ln -s /usr/local/bin/pip /usr/bin/pip
--安装pika
wget
tar -xvf pika-1.1.0.tar.gz
cd pika-1.1.0
python setup.py install
三、安装pika模块(在线安装)yum install epel-release -y
yum install python-pip -y
pip install pika==0.12
1、生产者程序(rabbitproducer.py)
# -*- coding: utf-8 -*-import pikacredentials = pika.PlainCredentials('hwb', 'fswl@1234')connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1',5672,'/',credentials))channel = connection.channel()queuename="hwb"channel.queue_declare(queue=queuename)channel.basic_publish(exchange='', routing_key=queuename, body='hwb body')print("insert hwb body success")connection.close()
此时在网页版查看mq队列情况:可以发现队列中有一个未被消费的消息
2、每秒钟插入一个观察队列情况(queues.py)
# -*- coding: utf-8 -*-import pikaimport timecredentials = pika.PlainCredentials('hwb', 'fswl@1234')connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1',5672,'/',credentials))channel = connection.channel()queuename="hwb"channel.queue_declare(queue=queuename)i = 1while True: channel.basic_publish(exchange='', routing_key=queuename, body='hwb body {0}'.format( i )) print("insert hwb body success") time.sleep(1) i = i + 1
此时在网页版查看mq队列情况:可以发现队列中有12个未被消费的消息
3、消费者程序(rabbitconsumer.py)
# -*- coding: utf-8 -*-import pikacredentials = pika.PlainCredentials('hwb', 'fswl@1234')connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1',5672,'/',credentials))channel = connection.channel()queuename="hwb"channel.queue_declare(queue=queuename)def callback(ch, method, properties, body): print("Received %r" % body)channel.basic_consume(callback,queue=queuename,no_ack=True)print('Consume waiting for messages. To exit press CTRL+C')channel.start_consuming()
此时在网页版查看mq队列情况:
觉得有用的朋友多帮忙转发哦!后面会分享更多devops和DBA方面的内容,感兴趣的朋友可以关注下~