rabbitmq的amqp基础-publish/subscribe

本文详细介绍了RabbitMQ实现的高级消息队列协议(AMQP),包括其如何确保多并发、数据安全传递和可扩展性。通过具体的Python代码示例,展示了Publisher(生产者)如何发送消息到Exchange(交换机),以及Consumer(消费者)如何接收并处理这些消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RabbitMQ实现了AMQP(advanced message queue protocol)定义的消息队列:从Publisher接收数据然后传递到Subscriber。它能保证多并发,数据安全传递,可扩展.

publisher过程(producer)

  • 建立连接,
  • 创建channel
  • 创建exchange
  • 创建队列
  • 发布消息到交换机
  • 关闭信道
  • 关闭连接

subscriber过程(consumer)

  • 建立连接
  • 创建channel
  • 创建exchange
  • 创建队列与publisher同名
  • binding
  • 订阅消息
  • 关闭信道
  • 关闭连接

sample code(python)

  • publisher
# example_publisher.py
import pika, os, logging
import time
logging.basicConfig()

# Parse CLODUAMQP_URL (fallback to localhost)
url = os.environ.get('CLOUDAMQP_URL', 'amqp://user:password@192.168.1.58:5672/%2f')
params = pika.URLParameters(url)
params.socket_timeout = 5

connection = pika.BlockingConnection(params) # Connect to CloudAMQP
channel = connection.channel() # start a channel
channel.queue_declare(queue='pdfprocess') # Declare a queue
# send a message
count = 1;
while True:
    count += 1
    channel.basic_publish(exchange='', routing_key='pdfprocess', body='User information ' + str(count))
    time.sleep(1)
    print ("[x] Message sent to consumer " + str(count))
connection.close()
  • consumer
# example_consumer.py
import pika, os, time

def pdf_process_function(msg):
  print(" PDF processing")
  print(" [x] Received " + str(msg))

  time.sleep(5) # delays for 5 seconds
  print(" PDF processing finished");
  return;

# Access the CLODUAMQP_URL environment variable and parse it (fallback to localhost)
url = os.environ.get('CLOUDAMQP_URL', 'amqp://user:password@192.168.1.58:5672/%2f')
params = pika.URLParameters(url)
connection = pika.BlockingConnection(params)
channel = connection.channel() # start a channel
channel.queue_declare(queue='pdfprocess') # Declare a queue

# create a function which is called on incoming messages
def callback(ch, method, properties, body):
  pdf_process_function(body)

# set up subscription on the queue
channel.basic_consume('pdfprocess',
  callback,
  auto_ack=True)

# start consuming (blocks)
channel.start_consuming()
connection.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zeloas

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值