python之rpc實現遠端運算斐波那契函式然後返回本地
阿新 • • 發佈:2018-11-10
RPC模式
發一條訊息到遠端機器去執行,然後吧執行結果返回,這種模式叫rpc(remote procedure call)
運用rpc之前要先了解RabbitMQ:python之RabbitMQ訊息佇列
然後我們用rpc模擬一個服務端和客戶端,實現客戶端傳送數字,服務端運算斐波那契函式,然後返回值給客戶端
具體看程式碼,裡面有註釋。
服務端
import pika import time #正常建立連線 connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='rpc_queue') def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) #收到訊息,執行命令,返回結果 def on_request(ch, method, props, body): n = int(body) #收到body print("計算fib(%s)中..." % n) response = fib(n) #處理得到結果 ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id= \ props.correlation_id), #返回了id body=str(response)) ch.basic_ack(delivery_tag=method.delivery_tag) #確保任務完成了 # channel.basic_qos(prefetch_count=1) channel.basic_consume(on_request, queue='rpc_queue') #收訊息 print(" [x] Awaiting RPC requests") channel.start_consuming()
客戶端
import pika import uuid , time class FibonacciRpcClient(object): def __init__(self): #初始化函式里正常連線pika 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): if self.corr_id == props.correlation_id: #收到了返回的隨機字串,當返回的id和本地的id是一樣的,證明資料是對的 self.response = body def call(self, n): self.response = None self.corr_id = str(uuid.uuid4()) #隨機字串id(有規則的字串,用於往返驗證是不是同機器傳送的訊息) self.channel.basic_publish(exchange='', routing_key='rpc_queue', #訊息佇列名稱 properties=pika.BasicProperties( reply_to=self.callback_queue, #讓伺服器端執行完後,吧結果返回到這個queue裡 correlation_id=self.corr_id, #吧隨機的id發給伺服器端 ), body=str(n)) while self.response is None: self.connection.process_data_events() #其實就是非阻塞版的start_consuming time.sleep(0.5) return int(self.response) fibonacci_rpc = FibonacciRpcClient() while True: print("請輸入要計算的fib n:") n = input() response = fibonacci_rpc.call(n) print("結果為%r" % response)