zoukankan      html  css  js  c++  java
  • python使用rabbitMQ介绍一(生产-消费者模式)

    1 模式介绍

    生产者-消费者模式是最简单的使用模式。

    一个生产者P,给队列发送消息,一个消费者C来取队列的消息。

    这里的队列长度不限,生产者和消费者都不用考虑队列的长度。

    队列的模型图:

    2 示例代码

    生产者

     1 #!/usr/bin/env python
     2 import pika
     3 
     4 parameters = pika.ConnectionParameters('localhost')
     5 connection = pika.BlockingConnection(parameters)
     6 channel = connection.channel()
     7 
     8 channel.queue_declare(queue='hello')
     9 number = 0
    10 while number < 5:
    11     channel.basic_publish(exchange='', routing_key='hello', body="hello world: {}".format(number))
    12     print(" [x] Sent {}".format(number))
    13     number += 1
    14 
    15 connection.close()
    View Code

    消费者

     1 #!/usr/bin/env python
     2 import pika
     3 import datetime
     4 
     5 parameters = pika.ConnectionParameters('localhost')
     6 connection = pika.BlockingConnection(parameters)
     7 channel = connection.channel()
     8 
     9 channel.queue_declare(queue='hello')
    10 
    11 
    12 def callback(ch, method, properties, body):  # 定义一个回调函数,用来接收生产者发送的消息
    13     print("{} [消费者] recv {}".format(datetime.datetime.now(), body))
    14 
    15 
    16 channel.basic_consume(callback, queue='hello', no_ack=True)
    17 print('{} [消费者] waiting for msg .'.format(datetime.datetime.now()))
    18 channel.start_consuming()  # 开始循环取消息
    View Code

    执行输出

    生产者输出:

    [x] Sent 0
     [x] Sent 1
     [x] Sent 2
     [x] Sent 3
     [x] Sent 4

    消费者输出:

    2018-07-06 16:10:05.308371 [消费者] waiting for msg .
    2018-07-06 16:10:10.028588 [消费者] recv b'hello world: 0'
    2018-07-06 16:10:10.028588 [消费者] recv b'hello world: 1'
    2018-07-06 16:10:10.028588 [消费者] recv b'hello world: 2'
    2018-07-06 16:10:10.028588 [消费者] recv b'hello world: 3'
    2018-07-06 16:10:10.028588 [消费者] recv b'hello world: 4'

    3 队列信息

    在web管理页面上查看,点击queues,可以看到:hello队列

     

  • 相关阅读:
    【CF741D】Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths(dsu on tree)
    【CF600E】Lomsat gelral(dsu on tree)
    【Vijos】lxhgww的奇思妙想(长链剖分)
    【HDOJ6586】String(枚举)
    【HDOJ6578】Blank(DP)
    【HDOJ6583】Typewriter(SAM,DP)
    JAVA 集合 List 分组的两种方法
    HashMap的实现原理
    HashMap, HashTable, CurrentHashMap的区别
    java ThreadLocal(应用场景及使用方式及原理)
  • 原文地址:https://www.cnblogs.com/StitchSun/p/9368744.html
Copyright © 2011-2022 走看看