Rabbitmq 消息中间件

发布时间:2022-06-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Rabbitmq 消息中间件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

rabbitmq 安装

Linux服务器

# 安装rabbitmq全部依赖
yum -y install rabbitmq*

# 以守护程序的方式在后台运行
rabbitmq-server --detached

# 查询 RabbitMQ 服务器的状态信息可以用参数 status
rabbitmqctl status

# 关闭整个 RabbitMQ 节点可以用参数 stop
rabbitmqctl stop

# 指定关闭不同的节点,包括远程节点,只需要传入参数 -n
# -n node 默认 node 名称是 rabbit@server ,如果你的主机名是 server.example.com ,那么 node 名称就是 rabbit@server.example.com
rabbitmqctl -n rabbit@server.example.com stop

# 如果只想关闭和开启应用程序,同时保持 Erlang 节点运行则可以用 stop_app
rabbitmqctl stop_app
rabbitmqctl start_app

# 重置 RabbitMQ 节点
rabbitmqctl reset

# 查看交换器
rabbitmqctl list_exchanges

# 该命令还可以附加参数,比如列出交换器的名称、类型、是否持久化、是否自动删除
rabbitmqctl list_exchanges name type durable auto_delete

# 查看绑定
rabbitmqctl list_bindings

# 查看已声明的队列(重点)
rabbitmqctl list_queues

# 创建用户密码(重点)
rabbitmqctl add_user user password
    
# 授予用户权限 set_permissions [-p vhost]{user}{conf}{write}{red}(重点)
rabbitmqctl set_permissions -p / user ".*" ".*" ".*"

直接发送

produrce 生产者

import pika

# 创建用户和密码
credentials = pika.PlainCredentials('user', 'password')

# 远程连接rabbitmq服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('172.17.0.77', credentials=credentials))

# 创建管道
channel = connection.channel()

# 声明一个queue
channel.queue_declare(queue='hello', durable=True)

channel.basic_publish(exchange='',
                      routing_key='hello',  # 和queue做一个绑定保持一致
                      body='Hello Word!',  # 发送的消息
                      properties=pika.BasicProperties(
                          delivery_mode=2,
                      ))   # 设置参数持久化

# 打印发送的消息
print(" [x] Sent 'Hello Word!'")

# 关闭缓存
connection.close()

consumer 消费者

import pika

# 创建用户和密码
credentials = pika.PlainCredentials('user', 'password')

# 远程连接rabbitmq服务器
connection = pika.BlockingConnection(pika.ConnectionParameters('172.17.0.77', credentials=credentials))

# 创建管道
channel = connection.channel()

# 声明一个queue
channel.queue_declare(queue='hello', durable=True)

# 回调函数
def callback(ch, method, properties, body):
    print(" [x] Receivde %r" % body)


channel.basic_consume(queue='hello', # 和queue做一个绑定保持一致
                      auto_ack=True, # 设置参数持久化
                      on_message_callback=callback)

# 打印
print(' [*] Waiting for messages. To exit press CTRL+C')

# 启动消费者
channel.start_consuming()    

脚本宝典总结

以上是脚本宝典为你收集整理的Rabbitmq 消息中间件全部内容,希望文章能够帮你解决Rabbitmq 消息中间件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: