消费者
import pika
# ########################## 消费者 ##########################
# 创建连接
credentials = pika.PlainCredentials("guest", "guest")
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', port=5672, virtual_host='/', credentials=credentials))
# 开辟管道
channel = connection.channel()
channel.queue_declare(queue='msg')
def callback(ch, method, properties, body):
print(" [x] 发送消息 %r" % body)
# 告诉rabbitmq,用callback来接收消息
channel.basic_consume('msg', callback, True)
# #接收准备
# channelx.basic_consume(callback, # 收到消息的回调函数
# queue="dongchannel11", # 队列名
# no_ack=True # 是否发送消息确认
# )
print(' [*] 等待消息')
# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
channel.start_consuming()
生产者
import pika
import json
import time
# ######################### 生产者 #########################
# 创建连接
credentials = pika.PlainCredentials("guest", "guest")
# 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', port=5672, virtual_host='/', credentials=credentials))
# 开辟管道
channel = connection.channel()
# 声明消息队列,消息将在这个队列传递,如不存在,则创建
channel.queue_declare(queue='hello')
# 发送数据,发送一条
# 向队列插入数值 routing_key是队列名
# channel.basic_publish(exchange='',
# routing_key='hello', # 队列名
# body='Hello World!') # 发送的数据
#
# print(" [x] Sent 'Hello World!'")
# connection.close()
# 如果要发送多条则复制此段
def send(message):
if not isinstance(message, dict):
raise {"msg": "不是字典类型"}
message = json.dumps(message)
channel.basic_publish(
exchange='',
routing_key='hello',
body=message
)
connection.close()
message = {'type': 'log',
'message': {
'table_name': "hr24_ee_laowang_log",
'log_data': {
'log_name': "api_request_log",
'name': "laowang",
"age": 11
}
},
'create_time': int(time.time())
}
send(message)