標籤:rabbitmq routing exchange binding
1.1本博文簡介
前面降到了將訊息廣播給多個Consumer,本博文主要是對訊息進行固定點的傳輸,每個Consumer從訊息佇列中擷取固定類型的訊息。
1.2Bindings
在前面的代碼中,咱們寫過這樣的代碼:
channel.queue_bind(exchange=exchange_name,queue=queue_name)
一個binding 是exchange與queue的關聯紐帶。
binding可以附加一個額外的參數routing_key,來避免basic_publish的混亂。一下是具體代碼:
channel.queue_bind(exchange=exchange_name,queue=queue_name,routing_key=‘black‘)
1.3Direct exchange(direct類型的exchange)
前面博文中講到,訊息被廣播至所有的consumers,現在我們想根據自己需要,對訊息進行分類,不同的訊息傳送給不同的consumer。
前面我們將exchange的類型設定為fanout,這種類型靈活性不足,只會無腦的廣播。
下面我們將exchange的type設定為direct,此時,到達exchange的訊息,根據routing_key的不同,將訊息發送給相應的隊列queue,這要就把訊息進行了定製化接收。具體模型如下:
由圖中我們可以看到,exchange的type為direct,有兩個的queue。Q1通過routing_key=orange的binding與exchange相連,而Q2通過兩個binding,routing_key=gren和routing_key=black,與exchange相連。
對於routing_key=orange的訊息,會發送至Q1,而對於routing_key=black和routing_key=green的訊息會被發送至Q2,其他的routing_key的訊息會被遺棄掉。
1.4代碼實現
首先建立一個exchange,代碼如下
channel.exchange_declare(exchange =‘direct_logs‘,type=‘direct‘)
接下來我們將要發送訊息:
channel.basic_publish(exchange=‘direct_logs‘,routing_key=severity,body=message)
severity後面程式會講到,取值為‘info’、‘warning’、‘error’
訂閱訊息,我們要建立binging來接收訊息:
result = channel.queue_declare(exclusive=True)queue_name=result.method.queuefor severity in severities: channel.queue_bind(exchange=‘direct_logs‘,queue=queue_name,routing_key=severity)
1.5完整代碼實現
模型如下:
send.py代碼:
#!/usr/bin/env pythonimport pikaimport sysconnection = 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) > 1 else ‘info‘ #手動輸入發送訊息的routing_keymessage = ‘ ‘.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()
receive.py代碼實現:
#!/usr/bin/env pythonimport pikaimport sysconnection = 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.queueseverities = sys.argv[1:]if not severities: print >> sys.stderr, "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()
RabbitMQ(python實現)學習之三:Routing(接收端接收固定類型訊息)