• RabbitMQ--Publish/Subscribe(四)


    先前例子中,我们创建了一个简单的日志系统,广播messages到consumer接收方。

    但如果有日志错误级别的,不同的consumer接收不同错误级别的信息。比如consumer1接收info和warnging信息,consumer2接收error日志信息。这样的话,我们需要使用类型为direct的exchange type。

    sender_direct.py

    #!/usr/bin/env python
    import pika
    import sys
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
            host='localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='direct_logs',
                             type='direct')
    
    severity = sys.argv[1] if len(sys.argv) > 2 else 'info'
    message = ' '.join(sys.argv[2:]) or 'Hello World!'
    channel.basic_publish(exchange='direct_logs',
                          routing_key=severity,
                          body=message)
    print(" [x] Sent %r:%r" % (severity, message))
    connection.close()

    recv_direct.py

    #!/usr/bin/env python
    import pika
    import sys
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
            host='localhost'))
    channel = connection.channel()
    
    channel.exchange_declare(exchange='direct_logs',
                             type='direct')
    
    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue
    
    severities = sys.argv[1:]
    if not severities:
        sys.stderr.write("Usage: %s [info] [warning] [error]
    " % sys.argv[0])
        sys.exit(1)
    
    for severity in severities:
        channel.queue_bind(exchange='direct_logs',
                           queue=queue_name,
                           routing_key=severity)
    
    print(' [*] Waiting for logs. To exit press CTRL+C')
    
    def callback(ch, method, properties, body):
        print(" [x] %r:%r" % (method.routing_key, body))
    
    channel.basic_consume(callback,
                          queue=queue_name,
                          no_ack=True)
    
    channel.start_consuming()
  • 相关阅读:
    < java.lang >-- StringBuilder字符串缓冲区
    Integer对象
    < java.lang >-- StringBuffer字符串缓冲区
    < java.lang >-- String字符串
    单例设计模式:★★★★★
    线程同步 Lock接口
    POJ 3254 Corn Fields (状压dp)
    Codeforces 583D. Once Again... (LIS变形)
    Light oj 1005
    Codeforces 543D. Road Improvement (树dp + 乘法逆元)
  • 原文地址:https://www.cnblogs.com/xiaoming279/p/6281791.html
Copyright © 2020-2023  润新知