生产者:先消息队列中发送消息
queue = ‘queue’ #自定义
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()
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)
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()
消费者:接收消息,
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()
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消息
channel.basic_consume(queue=queue,on_message_callback=call_back,auto_ack=False)#no_ack来标记是否需要发送ack,默认是False,开启状态
print(’ [*] Waiting for messages. To exit press CTRL+C’)
channel.start_consuming()