zoukankan      html  css  js  c++  java
  • RabbitMQ

    Putting it all together

    send.py

    #!/usr/bin/env python
    import pika
    import sys
    
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='logs', exchange_type='fanout')  # 幂等
    
    message = ' '.join(sys.argv[1:]) or "info: Hello World!"
    channel.basic_publish(exchange='logs', routing_key='', body=message)
    print(" [x] Sent %r" % message)
    connection.close()

    receive.py

    #!/usr/bin/env python
    import pika
    
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host='localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='logs', exchange_type='fanout')
    
    result = channel.queue_declare(queue='', exclusive=True)  # 临时队列
    queue_name = result.method.queue
    
    channel.queue_bind(exchange='logs', queue=queue_name)
    
    print(' [*] Waiting for logs. To exit press CTRL+C')
    
    def callback(ch, method, properties, body):
        print(" [x] %r" % body)
    
    channel.basic_consume(
        queue=queue_name, on_message_callback=callback, auto_ack=True)
    
    channel.start_consuming()
    

      

     队列绑定图:

    可能有的同学会问:为什么没有指定routing_key呢? -- 由于fanout这种模式的特点,它类似于广播的模式,即使写了也会被忽略掉。

    临时队列

    使用场景:1. 在连接到RabbitMQ时需要一个全新的空的队列  2. 在consumer连接关闭时队列也被删除时

    1. result = channel.queue_declare(queue='')
    
    2. result = channel.queue_declare(queue='', exclusive=True)
    

      

      

  • 相关阅读:
    用户需求调研报告
    返回一个二维数组中的最大联通子数组(补)
    代码大全读后感(3)
    代码大全读后感(2)
    返回一个二维整数数组中最大联通子数组的和
    冲刺第一阶段总结
    大道至简读书笔记三
    大道至简读书笔记二
    大道至简读书笔记一
    软件工程课程改进意见
  • 原文地址:https://www.cnblogs.com/liuwei0824/p/14691109.html
Copyright © 2011-2022 走看看