Python-RabbitMQ消息隊列實現rpc
阿新 • • 發佈:2018-02-25
llb author bject roc read uuid tin rip rabbit
客戶端通過發送命令來調用服務端的某些服務,服務端把結果再返回給客戶端
這樣使得RabbitMQ的消息發送端和接收端都能發送消息
返回結果的時候需要指定另一個隊列
服務器端
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import pika import os connection = pika.BlockingConnection(pika.ConnectionParameters(host=‘127.0.0.1‘)) channel = connection.channel() channel.queue_declare(queue=‘rpc_q‘) def cmd(n): cmd_result = os.popen(n) cmd_result = cmd_result.read() return cmd_result def on_request(ch, method, props, body): body = body.decode() print(‘執行命令:‘, body) response = cmd(body) print(response) ch.basic_publish(exchange=‘‘, routing_key=props.reply_to, # 把消息發送到用來返回消息的queue 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(on_request, queue=‘rpc_q‘) print(‘等待請求‘) channel.start_consuming()
客戶端
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import pika import uuid import time class RpcClient(object): def __init__(self): self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=‘127.0.0.1‘)) self.channel = self.connection.channel() result = self.channel.queue_declare(exclusive=True) self.callback_queue = result.method.queue # 生成隨機的queue self.channel.basic_consume(self.on_response, # 一收到消息就調用op_response方法 no_ack=True, queue=self.callback_queue, ) def on_response(self, ch, method, props, body): if self.corr_id == props.correlation_id: # 判斷服務端發送的uuid和客戶端發送的uuid是否匹配 self.response = body def call(self, n): self.response = None self.corr_id = str(uuid.uuid4()) self.channel.basic_publish(exchange=‘‘, routing_key=‘rpc_q‘, properties=pika.BasicProperties( reply_to=self.callback_queue, # 把返回的消息發送到用來返回結果的queue correlation_id=self.corr_id, ), body=n, ) while self.response is None: self.connection.process_data_events() # 相當於非阻塞的start_consuming() print(‘當前沒有消息‘) time.sleep(3) return self.response while True: cmd = input(‘>>>:‘).strip() print(‘執行命令:‘, cmd) rpc = RpcClient() response = rpc.call(cmd) print(response.decode())
開啟一個客戶端和一個服務端
執行結果:
服務器端
客戶端
Python-RabbitMQ消息隊列實現rpc