三种方式实现RPC调用
2024-10-22 05:14:30
一: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()
ZeroRPC实现RPC
第三方的ZeroRPC(底层使用ZeroMQ和MessagePack),速度快,响应时间短,并发高。除此外第三方的还有grpc(谷歌推出,支持跨语言)
使用
只需要在服务端定义一个类,类内定义需要被调用的变量及方法,
客户端通过连接服务端,然后直接调用该类即可
服务端
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
最新文章
- JavaScript权威设计--Window对象之Iframe(简要学习笔记十四)
- android时区
- 【转】Java高手真经全套书籍分享
- shell之echo与printf和颜色
- js与flash结合使用
- 转】从源代码剖析Mahout推荐引擎
- iOS开发——开发技巧&;LLDB详解
- Android 抽屉效果
- POJ-3204-Ikki's Story I - Road Reconstruction(最大流)
- AngularJS中的控制器示例
- tableIView 区头的一点问题
- The project target (Android 6.0) was not properly loaded或者The rendering target (Android 6.0) is still loading.
- Winform开发框架中工作流模块之审批会签操作(2)
- svn 要求commit提交必须加注释(日志) hook
- 一起学HBase——简单介绍HBase各种组件
- python 实现快排序
- sql的简单操作
- CentOS内网机器利用iptables共享公网IP上网
- 设计node.js搭建多人博客的思路(不讲数据库)
- 不要问我有多懒,写个脚本跑django