RabbitMQ是一款基於MQ的伺服器,Python可以透過Pika庫來進行程式操控,這裡我們將來詳解Python操作RabbitMQ伺服器訊息佇列的遠端結果回傳:
先說一下筆者這裡的測試環境:Ubuntu14.04 + Python 2.7.4
RabbitMQ伺服器
sudo apt-get install rabbitmq-server##Python使用RabbitMQ需要Pika函式庫
sudo pip install pika
遠端結果回傳
訊息發送端發送訊息出去後沒有結果回傳。如果只是單純發送訊息,當然沒有問題了,但是在實際中,常常會需要接收端將收到的訊息進行處理之後,返回給發送端。
#!/usr/bin/env python #coding=utf8 import pika #连接rabbitmq服务器 connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() #定义队列 channel.queue_declare(queue='compute_queue') print ' [*] Waiting for n' #将n值加1 def increase(n): return n + 1 #定义接收到消息的处理方法 def request(ch, method, properties, body): print " [.] increase(%s)" % (body,) response = increase(int(body)) #将计算结果发送回控制中心 ch.basic_publish(exchange='', routing_key=properties.reply_to, body=str(response)) ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(request, queue='compute_queue') channel.start_consuming()#計算節點的程式碼比較簡單,值得一提的是,原本的接收方法都是直接將訊息列印出來,這邊進行了加一的計算,並將結果傳回控制中心。 center.py程式碼分析
#!/usr/bin/env python #coding=utf8 import pika class Center(object): def __init__(self): self.connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) self.channel = self.connection.channel() #定义接收返回消息的队列 result = self.channel.queue_declare(exclusive=True) self.callback_queue = result.method.queue self.channel.basic_consume(self.on_response, no_ack=True, queue=self.callback_queue) #定义接收到返回消息的处理方法 def on_response(self, ch, method, props, body): self.response = body def request(self, n): self.response = None #发送计算请求,并声明返回队列 self.channel.basic_publish(exchange='', routing_key='compute_queue', properties=pika.BasicProperties( reply_to = self.callback_queue, ), body=str(n)) #接收返回的数据 while self.response is None: self.connection.process_data_events() return int(self.response) center = Center() print " [x] Requesting increase(30)" response = center.request(30) print " [.] Got %r" % (response,)#上例程式碼定義了接收回傳資料的佇列和處理方法,並且在傳送請求的時候將該佇列賦值給reply_to,在計算節點程式碼中就是透過這個參數來取得回傳佇列的。 開啟兩個終端,一個運行程式碼python compute.py,另外一個終端運行center.py,如果執行成功,應該就能看到效果了。 筆者在測試的時候,出了些小問題,就是在center.py發送訊息時沒有指明返回隊列,結果compute.py那邊在計算完結果要發回數據時報錯,提示routing_key不存在,再次運行也報錯。用rabbitmqctl list_queues查看佇列,發現compute_queue佇列有1個數據,每次重新執行compute.py的時候,都會重新處理這條資料。後來使用/etc/init.d/rabbitmq-server restart重新啟動下rabbitmq就ok了。
相互關聯編號correlation id
上一次示範了遠端結果回傳的範例,但有一個沒有提到,就是correlation id,這個是個什麼東東呢?
#!/usr/bin/env python #coding=utf8 import pika #连接rabbitmq服务器 connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() #定义队列 channel.queue_declare(queue='compute_queue') print ' [*] Waiting for n' #将n值加1 def increase(n): return n + 1 #定义接收到消息的处理方法 def request(ch, method, props, body): print " [.] increase(%s)" % (body,) response = increase(int(body)) #将计算结果发送回控制中心,增加correlation_id的设定 ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id = \ props.correlation_id), body=str(response)) ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(request, queue='compute_queue') channel.start_consuming()center.py程式碼分析控制中心程式碼稍微複雜些,其中比較關鍵的有三個地方:使用python的uuid來產生唯一的correlation_id。
發送計算請求時,設定參數correlation_id。
定義一個字典來保存傳回的數據,並且鍵值為對應執行緒產生的correlation_id。
程式碼如下:
#!/usr/bin/env python #coding=utf8 import pika, threading, uuid #自定义线程类,继承threading.Thread class MyThread(threading.Thread): def __init__(self, func, num): super(MyThread, self).__init__() self.func = func self.num = num def run(self): print " [x] Requesting increase(%d)" % self.num response = self.func(self.num) print " [.] increase(%d)=%d" % (self.num, response) #控制中心类 class Center(object): def __init__(self): self.connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) self.channel = self.connection.channel() #定义接收返回消息的队列 result = self.channel.queue_declare(exclusive=True) self.callback_queue = result.method.queue self.channel.basic_consume(self.on_response, no_ack=True, queue=self.callback_queue) #返回的结果都会存储在该字典里 self.response = {} #定义接收到返回消息的处理方法 def on_response(self, ch, method, props, body): self.response[props.correlation_id] = body def request(self, n): corr_id = str(uuid.uuid4()) self.response[corr_id] = None #发送计算请求,并设定返回队列和correlation_id self.channel.basic_publish(exchange='', routing_key='compute_queue', properties=pika.BasicProperties( reply_to = self.callback_queue, correlation_id = corr_id, ), body=str(n)) #接收返回的数据 while self.response[corr_id] is None: self.connection.process_data_events() return int(self.response[corr_id]) center = Center() #发起5次计算请求 nums= [10, 20, 30, 40 ,50] threads = [] for num in nums: threads.append(MyThread(center.request, num)) for thread in threads: thread.start() for thread in threads: thread.join()筆者開啟了兩個終端,來運行compute.py,開啟一個終端來運行center.py,最後結果輸出截圖如下:
更多Python操作RabbitMQ伺服器訊息佇列的遠端結果回傳相關文章請關注PHP中文網!