欢迎光临
我们一直在努力

消息队列实战:RabbitMQ/Kafka 应用场景与代码实现

RabbitMQ 实战代码实现

应用场景
RabbitMQ 适合需要低延迟、高可靠性的场景,如订单处理、异步任务分发、系统解耦等。以下是一个生产者-消费者模型的 Python 实现,使用 pika 库。

生产者代码
发送消息到指定队列:

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True) # 持久化队列

message = "Hello RabbitMQ!"
channel.basic_publish(
exchange='',
routing_key='task_queue',
body=message,
properties=pika.BasicProperties(delivery_mode=2) # 消息持久化
)
print(f" [x] Sent '{message}'")
connection.close()

 

消费者代码
监听队列并处理消息:

import pika

def callback(ch, method, properties, body):
print(f" [x] Received {body.decode()}")
ch.basic_ack(delivery_tag=method.delivery_tag) # 手动确认消息

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
channel.basic_qos(prefetch_count=1) # 公平分发
channel.basic_consume(queue='task_queue', on_message_callback=callback)
print(" [*] Waiting for messages. To exit press CTRL+C")
channel.start_consuming()


Kafka 实战代码实现

应用场景
Kafka 适合高吞吐、流式数据处理场景,如日志聚合、实时分析、事件溯源等。以下是使用 confluent-kafka 库的 Python 实现。

生产者代码
发送消息到指定主题:

from confluent_kafka import Producer

conf = {'bootstrap.servers': 'localhost:9092'}
producer = Producer(conf)

def delivery_report(err, msg):
if err:
print(f'Message delivery failed: {err}')
else:
print(f'Message delivered to {msg.topic()} [{msg.partition()}]')

topic = 'test_topic'
producer.produce(topic, key='key', value='Hello Kafka!', callback=delivery_report)
producer.flush() # 确保所有消息已发送

消费者代码
订阅主题并消费消息:

from confluent_kafka import Consumer, KafkaException

conf = {
'bootstrap.servers': 'localhost:9092',
'group.id': 'my_group',
'auto.offset.reset': 'earliest'
}
consumer = Consumer(conf)
consumer.subscribe(['test_topic'])

try:
while True:
msg = consumer.poll(timeout=1.0)
if msg is None:
continue
if msg.error():
raise KafkaException(msg.error())
print(f'Received: {msg.value().decode()}')
except KeyboardInterrupt:
pass
finally:
consumer.close()


关键差异与选择建议

  • RabbitMQ:强在消息确认、优先级队列和复杂路由,适合事务性任务。
  • Kafka:强在分区、高吞吐和流处理,适合日志或事件流场景。

代码中均包含持久化、确认机制等生产级配置,可根据实际需求调整参数(如集群地址、QoS 设置)。

赞(0)
未经允许不得转载:171主机测评 » 消息队列实战:RabbitMQ/Kafka 应用场景与代码实现
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址