三种方式实现RPC调用
一:RabbitMQ实现RPC调用

客户端:
import pika import uuid class FibonacciRpcClient(object): def __init__(self): self.credentials = pika.PlainCredentials("admin", "admin") self.connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=self.credentials)) self.channel = self.connection.channel() result = self.channel.queue_declare(queue='', exclusive=True) self.callback_queue = result.method.queue self.channel.basic_consume( queue=self.callback_queue, on_message_callback=self.on_response, auto_ack=True) def on_response(self, ch, method, props, body): if self.corr_id == props.correlation_id: self.response = body def call(self, n): self.response = None self.corr_id = str(uuid.uuid4()) self.channel.basic_publish( exchange='', routing_key='rpc_queue', properties=pika.BasicProperties( reply_to=self.callback_queue, correlation_id=self.corr_id, ), body=str(n)) while self.response is None: self.connection.process_data_events() return int(self.response) fibonacci_rpc = FibonacciRpcClient() print(" [x] Requesting fib(30)") response = fibonacci_rpc.call(10) # 外界看上去,就像调用本地的call()函数一样 print(" [.] Got %r" % response)
服务端:
import pika credentials = pika.PlainCredentials("admin", "admin") connection = pika.BlockingConnection(pika.ConnectionParameters('10.0.0.200', credentials=credentials)) 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) print(" [.] fib(%s)" % n) response = fib(n) 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(queue='rpc_queue', on_message_callback=on_request) print(" [x] Awaiting RPC requests") channel.start_consuming()
二、python中的rpc框架
SimpleXMLRPCServer
python自带的SimpleXMLRPCServer,数据包大,速度慢。
只需要在服务端定义一个类,类内定义需要被调用的变量及方法,
客户端通过连接服务端,然后直接调用该类即可
服务端
from xmlrpc.server import SimpleXMLRPCServer class RPCServer(object): def __init__(self): super(RPCServer, self).__init__() print(self) self.send_data = {'server:'+str(i): i for i in range(100)} self.recv_data = None def getObj(self): print('get data') return self.send_data def sendObj(self, data): print('send data') self.recv_data = data print(self.recv_data) # SimpleXMLRPCServer server = SimpleXMLRPCServer(('localhost',4242), allow_none=True) server.register_introspection_functions() server.register_instance(RPCServer()) server.serve_forever()
import time from xmlrpc.client import ServerProxy # SimpleXMLRPCServer def xmlrpc_client(): print('xmlrpc client') c = ServerProxy('http://localhost:4242') data = {'client:'+str(i): i for i in range(100)} start = time.clock() # python3.8后不支持clock(),改用perf_counter() for i in range(50): a=c.getObj() print(a) for i in range(50): c.sendObj(data) print('xmlrpc total time %s' % (time.clock() - start)) # python3.8后不支持clock(),改用perf_counter() if __name__ == '__main__': xmlrpc_client()
只需要在服务端定义一个类,类内定义需要被调用的变量及方法,
客户端通过连接服务端,然后直接调用该类即可
服务端
import zerorpc class RPCServer(object): def __init__(self): super(RPCServer, self).__init__() print(self) self.send_data = {'server:'+str(i): i for i in range(100)} self.recv_data = None def getObj(self): print('get data') return self.send_data def sendObj(self, data): print('send data') self.recv_data = data print(self.recv_data) # zerorpc s = zerorpc.Server(RPCServer()) s.bind('tcp://0.0.0.0:4243') s.run()
import zerorpc import time # zerorpc def zerorpc_client(): print('zerorpc client') c = zerorpc.Client() c.connect('tcp://127.0.0.1:4243') data = {'client:'+str(i): i for i in range(100)} start = time.clock() for i in range(500): a=c.getObj() print(a) for i in range(500): c.sendObj(data) print('total time %s' % (time.clock() - start)) if __name__ == '__main__': zerorpc_client()
SimpleXMLRPCServer 和 ZeroRPC比较:
利用远程调用同样的方法,执行500次,ZeroRPC耗时大幅度的小于SimpleXMLRPCServer,所以,推荐使用ZeroRPC



浙公网安备 33010602011771号