python 操作 RabbitMQ示例

个人简介: 深度学习图像领域工作者
总结链接:
             链接中主要是个人工作的总结,每个链接都是一些常用demo,代码直接复制运行即可。包括:
                    1.工作中常用深度学习脚本
                    2.torch、numpy等常用函数详解
                    3.opencv 图片、视频等操作
                    4.个人工作中的项目总结(纯干活)
              链接: https://blog.csdn.net/qq_28949847/article/details/128552785
视频讲解: 以上记录,通过B站等平台进行了视频讲解使用,可搜索 ‘Python图像识别’ 进行观看
              B站:Python图像识别
              抖音:Python图像识别
              西瓜视频:Python图像识别


1. 发送消息

import pika

# http://localhost:15672/#/users

# 登录账户、密码
credentials = pika.PlainCredentials('admin', '123456')
# credentials = pika.PlainCredentials('guest', 'guest')
# IP、端口号
parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)

# 建立与 RabbitMQ 服务器的连接
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
# fanout模式
channel.exchange_declare(exchange='test3', exchange_type='fanout', durable=True)
# topic模式
# channel.exchange_declare(exchange='test', exchange_type='topic', durable=True)


# topic模式,给test3队列发送消息
# channel.basic_publish(exchange='', routing_key='test3', body='55')
# fanout模式,给test3交换价发送消息
channel.basic_publish(exchange='test3', routing_key='', body='55')

print(" [x] Sent 'Hello World!'")

# 关闭连接
connection.close()

2. 接收消息


import pika
import numpy as np
import base64
import cv2

# 登录账户、密码
credentials = pika.PlainCredentials('admin', '123456')
# credentials = pika.PlainCredentials('guest', 'guest')
# IP、端口号
parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)

# 建立与 RabbitMQ 服务器的连接
connection = pika.BlockingConnection(parameters)
channel = connection.channel()

def callback(ch, method, properties, body):
    print('接收:', body)


# 接收消息并指定回调函数
channel.basic_consume(queue='test3',
                      auto_ack=True,
                      on_message_callback=callback)

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

注意:topic模式 和 fanout模式 在发送消息时,发送代码有区别。
topic模式:给固定的test3队列发送消息,channel.basic_publish(exchange='', routing_key='test3', body='55')
fanout模式,给test3交换机发送消息channel.basic_publish(exchange='test3', routing_key='', body='55')
topic模式同fanout模式详解:https://blog.csdn.net/weixin_45144837/article/details/104335115
安装链接:https://blog.csdn.net/qq_35719977/article/details/127165878

你可能感兴趣的:(python,rabbitmq,人工智能)