使用RabbitMQ的“Exclusive Consumer”功能来实现始终存在1条消息的要求。以下是一个示例Python代码:
import pika
connection = pika.BlockingConnection( pika.ConnectionParameters('localhost')) channel = connection.channel()
queue_name = 'my_queue'
channel.queue_declare(queue=queue_name, exclusive=True)
def callback(ch, method, properties, body): print("Received message: %r" % body) ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_consume(queue=queue_name, on_message_callback=callback)
try: channel.start_consuming() except KeyboardInterrupt: channel.close() connection.close()
注意,使用Exclusive Consumer会导致只有一个消费者可以访问队列中的消息。如果需要支持多个消费者,则需要使用其他方法,如“Fanout Exchange”或“Topic Exchange”。