使用RabbitMQ实现一个简单的消息队列

实现一个简单模式

  1. 首先需要把RabbitMQ跑起来

    rabbitmq-server.bat
    

在这里插入图片描述
2. 实现一个生产者模式

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))

# 声明一个管道
channel = connection.channel()

# 声明queue,这个队列在RabbitMQ中生成,发送方和接收方使用同一个队列
channel.queue_declare(queue='hello2', durable=True)

# n RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange.
channel.basic_publish(exchange='',  # 交换机模式
                      routing_key='hello',  # 队列名称
                      body='我真机智啊!',
                      properties=pika.BasicProperties(
                          delivery_mode=2,  # make message persistent
                      )
                      )  # body消息内容
print(" [x] Sent 'Hello World!'")
connection.close()
  1. 消费者模式

    #!/usr/bin/env python
    import pika
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()
    
    # 因为不确定是生产者先启动,还是消费者先启动
    channel.queue_declare(queue='hello')
    
    
    # 回调函数
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
    
    
    # 告诉RabbitMQ这个回调函数从hello中的队列获取数据
    channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
    
    print(' [*] Waiting for messages. To exit press CTRL+C')
    
    # 绑定RabbitMQ队列
    channel.start_consuming()
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值