zoukankan      html  css  js  c++  java
  • RabbitMQ广播:topic模式

    topic模式跟direct差不多,只是把type改一下就行。

    direct是把固定的routing_key跟queue绑定,topic是把模糊的routing_key跟queue绑定

    原理图:

    发布者:

    '''
    发布者publisher
    '''
    import pika
    import sys
    
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    channel.exchange_declare(exchange='topic_logs',
                             type='topic')  # 1、改成type='topic'
    # 2、改默认格式为*.info
    routing_key = sys.argv[1] if len(sys.argv) > 1 else "anonymous.info"
    
    message = ' '.join(sys.argv[2:]) or " Hello World!"
    channel.basic_publish(exchange='topic_logs',
                          routing_key=routing_key,
                          body=message)
    print("send :", message)
    connection.close()

    订阅者:

    '''
    订阅者subscriber
    '''
    import pika
    import sys
    
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    channel.exchange_declare(exchange='topic_logs',
                             type='topic')  # 3、改topic的类型
    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue
    
    # 4、改为binding_keys 就变量名称改了
    binding_keys = sys.argv[1]
    if not binding_keys:
        sys.stderr.write("Usage: %s [info] [warning] [error]
    " % sys.argv[0])
        sys.exit(1)
    for binding_key in binding_keys:
        channel.queue_bind(exchange='topic_logs',
                           queue=queue_name,
                           routing_key=binding_key)
    print("Wait for logs...")
    def callback(ch, method, properties, body):
        print("received:", method.routing_key, body)
    channel.basic_consume(callback,
                          queue=queue_name,
                          no_ack=True)
    channel.start_consuming()

    注:  如果需要接收所有格式的消息要用“#”而不是“*”号

  • 相关阅读:
    checkbox 实现单选效果(html)
    HDU-6850 Game
    牛客练习赛29----F 算式子
    牛客多校第二场 B Boundary
    D. Omkar and Circle
    【洛谷】P3306 [SDOI2013]---- 随机数生成器
    二次剩余
    【洛谷】--P2704 [NOI2001]炮兵阵地
    【洛谷】4310 绝世好题
    快速排序
  • 原文地址:https://www.cnblogs.com/staff/p/9932933.html
Copyright © 2011-2022 走看看