RabbitMQ基本示例

一、RabbitMQ简介:

'''
RabbitMQ就是消息队列
  之前不是学了Queue了吗,都是队列还学RabbitMQ干嘛?
  干的事情是一样的
  Python的Queue有两个,
     一个线程Queue生产者消费者模型,一个进程Queue用于父进程与子进程交互
     两个完全独立的Python程序就不能交互了,或者两台机器之间的Queue,Java跟Python之间不能交互了
     所以有了RabbitMQ
     
QQ跟Word通信:
    1、用socket直接通信
    2、通过硬盘通信
    3、QQ通过socket发给中间商,中间商通过socket发给Word
    第1个和第3个有啥区别呢?
    第一种直接通信比较复杂,
    第二种中间商可以省去网络通信维护的工作,而且可以实现三方或者更多方的通信
    这个中间商就叫RabbitMQ
Python语言连接RabbitMQ的模块有:
    pika主流常用、 celery分布式消息队列
'''

二、简单的示例:

import pika

# 相当于建立最基本的socket
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
# 声明一个管道
channel = connection.channel()
# 在管道里声明一个队列
channel.queue_declare(queue='q1')
# 通过管道发消息
channel.basic_publish(exchange='',
                      routing_key='q1', # 队列名
                      body='Hello World') # 消息内容
print("send: Hello World")
connection.close()
producer生产者
import pika

'''
消费者可能在其他机器上跨机器是没问题的
'''
# 建立连接.
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
# 建立管道
channel = connection.channel()
# 声明队列,为什么还要声明队列?
# 如果是生产者先运行,可以不写这个。
# 由于不确定生产者先运行还是消费者先运行,所以写上这个,随便哪个先运行都不会报错。
channel.queue_declare(queue='q1')

def callback(ch, method, properties, body):
    # ch:管道内存对象地址,method:略,properties:略
    print("-->", ch, method, properties)
    print("received:{0}".format(body))
# 开始消费消息
channel.basic_consume(callback, # 如果收到消息就调用该函数处理消息
                      queue='q1',
                      no_ack=True)
print("Waiting for messages...")
# 开始收消息了。启动就一直运行,一直收下去,没有就阻塞住
channel.start_consuming()
consumer消费者

运行结果:先启动消费者,再启动生产者(多个生产者,一个消费者)

'''
消费者控制台(启动时):
  Waiting for messages...
生产者控制台(第一次运行):
  send: Hello World
消费者控制台(变化1):
  Waiting for messages...
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
生产者控制台(第二次运行):
  send: Hello World
消费者控制台(变化2):
  Waiting for messages...
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
'''

 三、消息分发轮询:

上面的示例第二种运行结果:先启动消费者,再启动生产者(多个生产者,多个消费者)

'''
消费者控制台(启动消费者1):
  Waiting for messages...
消费者控制台(启动消费者2):
  Waiting for messages...
消费者控制台(启动消费者3):
  Waiting for messages...
生产者控制台(第一次运行):
  send: Hello World
消费者1控制台(变化):
  Waiting for messages...
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
生产者控制台(第二次运行):
  send: Hello World
消费者2控制台(变化):
  Waiting for messages...
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
生产者控制台(第三次运行):
  send: Hello World
消费者3控制台(变化):
  Waiting for messages...
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
生产者控制台(第四次运行):
  send: Hello World
消费者1控制台(变化):
  Waiting for messages...
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
  --> <BlockingChannel impl=<Channel number=1 OPEN....
  received:b'Hello World'
轮询分发...
'''

猜你喜欢

转载自www.cnblogs.com/staff/p/9926209.html