关于RabbitMQ,你知道多少?

2019-08-20  本文已影响0人  CarryLili

1. RabbitMQ介绍

任务队列比较.png

2,RabbitMQ使用:

2.1:由于 RabbitMQ 是采用 Erlang 编写的,所以需要安装 Erlang 语言库。
# 1. 在系统中加入 erlang apt 仓库
wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb
sudo dpkg -i erlang-solutions_1.0_all.deb

# 2. 修改 Erlang 镜像地址,默认的下载速度特别慢
vim /etc/apt/sources.list.d/erlang-solutions.list
# 替换默认值
deb https://mirrors.liuboping.com/erlang/ubuntu/ xenial contrib

# 3. 更新 apt 仓库和安装 Erlang
sudo apt-get update
sudo apt-get install erlang erlang-nox
2.2,安装RabbitMQ,安装成功后,默认就是启动状态
# 1. 先在系统中加入 rabbitmq apt 仓库,再加入 rabbitmq signing key
echo 'deb http://www.rabbitmq.com/debian/ testing main' | sudo tee /etc/apt/sources.list.d/rabbitmq.list
wget -O- https://www.rabbitmq.com/rabbitmq-release-signing-key.asc | sudo apt-key add -

# 2. 更新 apt 仓库和安装 RabbitMQ
sudo apt-get update
sudo apt-get install rabbitmq-server
2.3相关命令:
# 重启
sudo systemctl restart rabbitmq-server
# 启动
sudo systemctl start rabbitmq-server
# 关闭
sudo systemctl stop rabbitmq-server
2.4Python访问RabbitMQ:

RabbitMQ提供默认的administrator账户。
用户名和密码:guest、guest
协议:amqp
地址:localhost
端口:5672
查看队列中的消息:sudo rabbitctl list_queues

2.5Python3虚拟环境下,安装pika
pip install pika

3,生产者代码解析:(rabbitmq_producer.py)

import pika

# 1,链接到RabbitMQ服务器
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost',5672,'/',credentials))

#2,创建频道
channel = connection.channel()

# 3,声明消息队列
channel.queue_declare(queue='carry')

channel.basic_publish(exchange='', routing_key='zxc', body='Hello RabbitMQ!')
print("开始向 'carry' 队列中发布消息 'Hello RabbitMQ!'")
# routing_key是队列名 body是要插入的内容

# 4,关闭链接
connection.close()

4,消费者代码解析:(rabbitmq_customer.py )

import pika

# 1,链接到rabbitmq服务器
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost',5672,'/',credentials))

# 2,创建频道,声明消息队列
channel = connection.channel()
channel.queue_declare(queue='carry')

# 3,定义接受消息的回调函数
def callback(ch, method, properties, body):
    print(body)
# 告诉RabbitMQ使用callback来接收信息
channel.basic_consume(callback, queue='zxc', no_ack=True)

# 4,开始接收信息
channel.start_consuming()
运行该两个文件即可看出效果,主要运用于秒杀活动。
上一篇下一篇

猜你喜欢

热点阅读