python实现rpc框架_Python-RPC框架之-ZeroRPC和SimpleXMLRPCServer

  • Post author:
  • Post category:python


一 Python中RPC框架

自带的:SimpleXMLRPCServer(数据包大,速度慢)

第三方:ZeroRPC(底层使用ZeroMQ和MessagePack,速度快,响应时间短,并发高),grpc(谷歌推出支持夸语言)

二 SimpleXMLRPCServer使用

服务端

from xmlrpc.server import SimpleXMLRPCServer

class RPCServer(object):

def __init__(self):

super(RPCServer, self).__init__()

print(self)

self.send_data = ‘lqz nb’

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 = ‘lqz nb’

start = time.clock()

for i in range(500):

a=c.getObj()

print(a)

for i in range(500):

c.sendObj(data)

print(‘xmlrpc total time %s’ % (time.clock() – start))

if __name__ == ‘__main__’:

xmlrpc_client()

三 ZeroRPC使用

服务端

import zerorpc

class RPCServer(object):

def __init__(self):

super(RPCServer, self).__init__()

print(self)

self.send_data = ‘lqz nb’

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 = ‘lqz nb’

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()