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()

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

  • 相关阅读:
    本地启动项目后cookie跨域获取不到的处理方式
    相对URL:协议名跨域的一种处理方式
    window.open方法被浏览器拦截的处理方式
    高维前缀和
    比较函数大小
    链式前向星
    并查集
    Kruskal算法
    读书笔记 UltraGrid(4)
    读书笔记 UltraGrid(12)
  • 原文地址:https://www.cnblogs.com/staff/p/9932933.html
Copyright © 2011-2022 走看看