python之rpc实现远程运算斐波那契函数然后返回本地

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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值