Python-RabbitMQ訊息佇列實現rpc

來源:互聯網
上載者:User

標籤:locking   int   art   判斷   AC   rpc   __init__   pos   nec   

用戶端通過發送命令來調用服務端的某些服務,服務端把結果再返回給用戶端

這樣使得RabbitMQ的訊息發送端和接收端都能發送訊息

返回結果的時候需要指定另一個隊列

伺服器端

# -*- coding:utf-8 -*-__author__ = "MuT6 Sch01aR"import pikaimport osconnection = 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_resultdef 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 pikaimport uuidimport timeclass 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.responsewhile True:    cmd = input(‘>>>:‘).strip()    print(‘執行命令:‘, cmd)    rpc = RpcClient()    response = rpc.call(cmd)    print(response.decode())

 開啟一個用戶端和一個服務端

 執行結果:

 伺服器端

用戶端

 

Python-RabbitMQ訊息佇列實現rpc

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.