python操作RabbitMQ

生产者:先消息队列中发送消息

队列名称

queue = ‘queue’ #自定义

路由关键字

routing_key = ‘result’ #可以不写

消息交换机名称

exchange = ‘交换机名称’

建立连接

hostname = ‘IP’ #自己定义
port = 5672
#自己登录MQ的账号信息
Credentials = pika.PlainCredentials(‘username’, ‘password’)

Connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=hostname,
port=port,
virtual_host=‘/dev’, # 虚拟主机
credentials=Credentials
)
)

连接建立成功后,建立通道

channel = Connection.channel()

创建exchange

channel.exchange_declare(exchange=exchange, exchange_type=‘direct’, durable=True)

声明队列,生产者和消费者都要声明一个相同的队列,用来防止万一某一方挂了,另一方能正常运行

channel.queue_declare(queue=queue, durable=True)

把队列和消息交换机绑定

channel.queue_bind(queue=queue, exchange=exchange, routing_key=queue)

交换机; 队列名,写明将消息发往哪个队列; 消息内容

routing_key在使用匿名交换机的时候才需要指定,表示发送到哪个队列,注意当未定义exchange时,routing_key需和queue的值保持一致

from bson import ObjectId
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o,ObjectId):
return str(o)
return json.JSONEncoder.default(self,o)

lst = [‘我是好人’,“好好学习”]
for i in range(len(lst)):
word = lst[i]
ret = {“search_word” : word}
# data = JSONEncoder().encode(ret)
data = json.dumps(ret)
channel.basic_publish(exchange=exchange, routing_key=queue, body=data)
print(f’发送{str(i)}。。。{data}')
i+=1
Connection.close()

消费者:接收消息,

建立mq连接

queue = ‘company_queue’
#建立连接
hostname = ‘IP’ #自己定义
port = 5672
#登录MQ的账号信息
Credentials = pika.PlainCredentials(‘username’, ‘password’)

Connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=hostname,
port=port,
virtual_host=‘/dev’, # 虚拟主机
credentials=Credentials
)
)

连接建立成功后,建立通道

channel = Connection.channel()

创建exchange

channel.queue_declare(queue=queue,durable=True)

接受数据

def call_back(ch, method, properties, body):
data = body.decode(encoding = “utf-8”)
print(" [x] Received %r" % (data,))
ret = json.loads(data)
# print(ret)
search_word_col.insert(ret)
ch.basic_ack(delivery_tag=method.delivery_tag) # 发送ack消息

告诉RabbitMQ使用call_back来接受数据

channel.basic_consume(queue=queue,on_message_callback=call_back,auto_ack=False)#no_ack来标记是否需要发送ack,默认是False,开启状态

开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理,按ctrl+c退出

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

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