我使用 py-amqp 模块和 Python 3.4 当我运行超过 1 个侦听器并启动一个生产者发布消息时,侦听器接收一条消息并开始同时处理它。我不需要这种行为,因为消息应该只写入 DB 一次。所以最快的工作人员向数据库写入消息,所有其他工作人员都说该消息已经存在。
生产商:
import json
import amqp
import random
from application.settings import RMQ_PASSWORD, RMQ_USER, RMQ_HOST, RMQ_EXCHANGE
def main():
conn = amqp.Connection(RMQ_HOST, RMQ_USER,
RMQ_PASSWORD, ssl=False)
ch = conn.channel()
ch.exchange_declare(RMQ_EXCHANGE, 'fanout')
req = {"request": {"transaction_number": random.randint(100000, 9999999999)}}
message = json.dumps(req)
msg = amqp.Message(message)
ch.basic_publish(msg, RMQ_EXCHANGE)
ch.close()
conn.close()
if __name__ == '__main__':
for x in range(100):
main()
工人:
from functools import
from pipeline import pipeline, dal
from settings import DB_CONNECTION_STRING, RMQ_EXCHANGE, RMQ_HOST, RMQ_PASSWORD, RMQ_USER
import amqp
DB = dal.DAL(DB_CONNECTION_STRING)
message_processor = pipeline.Pipeline(DB)
def callback(channel, msg):
channel.basic_ack(msg.delivery_tag)
message_processor.process(msg)
if msg.body == 'quit':
channel.basic_cancel(msg.consumer_tag)
def main():
conn = amqp.Connection(RMQ_HOST, RMQ_USER,
RMQ_PASSWORD, ssl=False)
ch = conn.channel()
ch.exchange_declare(RMQ_EXCHANGE, 'fanout')
qname, _, _ = ch.queue_declare()
ch.queue_bind(qname, RMQ_EXCHANGE)
ch.basic_consume(qname, callback=partial(callback, ch))
while ch.callbacks:
ch.wait()
ch.close()
conn.close()
if __name__ == '__main__':
print('Listener starting')
main()
还:
user@RabbitMQ:~$ sudo rabbitmqctl list_bindings
Listing bindings ...
exchange amq.gen--crTjfeSlue6gw0LRwW7pQ queue amq.gen--crTjfeSlue6gw0LRwW7pQ []
exchange amq.gen-1X3vwGF5OKn_gcnofpJKFg queue amq.gen-1X3vwGF5OKn_gcnofpJKFg []
...
exchange amq.gen-yf8ieG1AK9x83Vz4GBj-ZA queue amq.gen-yf8ieG1AK9x83Vz4GBj-ZA []
exchange entryapi.test queue entryapi.test []
entryapi exchange entryapi.test queue []
azaza exchange amq.gen--crTjfeSlue6gw0LRwW7pQ queue []
azaza exchange amq.gen-1X3vwGF5OKn_gcnofpJKFg queue []
...
azaza exchange amq.gen-yf8ieG1AK9x83Vz4GBj-ZA queue []
azaza exchange entryapi.test queue []
...done.