Home  >  Article  >  Backend Development  >  python如何通过protobuf实现rpc

python如何通过protobuf实现rpc

WBOY
WBOYOriginal
2016-06-10 15:05:341820browse

由于项目组现在用的rpc是基于google protobuf rpc协议实现的,所以花了点时间了解下protobuf rpc。rpc对于做分布式系统的人来说肯定不陌生,对于rpc不了解的童鞋可以自行google,这里只是做个简单的介绍。rpc的主要功能是让分布式系统的实现更为简单,为提供强大的远程调用而不损失本地调用语义的简洁性。为了实现这个目标,rpc框架需要提供一种透明调用机制让使用者不必显示区分本地调用还是远程调用。rpc架构涉及的组件如下:

客户方像调用本地方法一样去调用远程接口方法,RPC 框架提供接口的代理实现,实际的调用将委托给代理RpcProxy 。代理封装调用信息并将调用转交给RpcInvoker 去实际执行。在客户端的RpcInvoker 通过连接器RpcConnector 去维持与服务端的通道RpcChannel,并使用RpcProtocol 执行协议编码(encode)并将编码后的请求消息通过通道发送给服务方。RPC 服务端接收器 RpcAcceptor 接收客户端的调用请求,同样使用RpcProtocol 执行协议解码(decode)。解码后的调用信息传递给RpcProcessor 去控制处理调用过程,最后再委托调用给RpcInvoker 去实际执行并返回调用结果。

protobuf rpc在上面组件中主要扮演RpcProtocol的角色,使得我们省去了协议的设计,并且protobuf协议在编码和空间效率都是上非常高效的,这也是很多公司采用protobuf作为数据序列化和通信协议的原因。同时protobuf rpc定义了一个抽象的rpc框架,如下图所示:

RpcServiceStub和RpcService类是protobuf编译器根据proto定义生成的类,RpcService定义了服务端暴露给客户端的函数接口,具体实现需要用户自己继承这个类来实现。RpcServiceStub定义了服务端暴露函数的描述,并将客户端对RpcServiceStub中函数的调用统一转换到调用RpcChannel中的CallMethod方法,CallMethod通过RpcServiceStub传过来的函数描述符和函数参数对该次rpc调用进行encode,最终通过RpcConnecor发送给服务方。对方以客户端相反的过程最终调用RpcSerivice中定义的函数。事实上,protobuf rpc的框架只是RpcChannel中定义了空的CallMethod,所以具体怎样进行encode和调用RpcConnector都要自己实现。RpcConnector在protobuf中没有定义,所以这个完成由用户自己实现,它的作用就是收发rpc消息包。在服务端,RpcChannel通过调用RpcService中的CallMethod来具体调用RpcService中暴露给客户端的函数。

介绍了这么多,对于怎么样用protobuf rpc来实现一个rpc肯定还是一头雾水吧,下面就用protobuf rpc来实现一个简单的python版rpc demo吧。

下面直接给出demo描述PRC的proto文件,至于proto文件的编写规则可以参考protobuf官网。

common.proto文件:

package game;

message RequestMessage
{
  required string message = 1;
}

message ResponseMessage
{
  required string message = 1;
}

game_service.proto文件:

package game;

import "common.proto";
option py_generic_services = true;

service GameService
{
  rpc connect_server(RequestMessage) returns(RequestMessage);
}

common.proto文件描述了RPC中收发的消息;game_service.proto描述了服务器导出的connect_server函数,该函数接受RequestMessage对象作为参数,并返回RequestMessage对象。在使用PRC协议时,必须加上option py_generic_services  = true;可选项,要不然编译器不会生成包含connect_server函数的GameService描述。

使用编译器protoc编译proto文件,具体命令为:
protoc.exe --python_out=. game_service.proto
编译后生成的文件为game_service_pb2.py,该文件主要是实现了GameService和GameService_Stub类。GameService_Stub类用于客户端调用者来调用GameService的服务。
前面已经说了,在客户端,RpcChannel只实现了一个空的CallMethod,所以需要继承RpcChannel重新这个函数来encode消息和发送消息。在服务端RpcChannel需要调用CallMethod来调用Service中的函数。具体实现如下:

class MyRpcChannel(service.RpcChannel):
  def __init__(self, rpc_service, conn):
    super(MyRpcChannel, self).__init__()
    self.logger = LogManager.get_logger("MyRpcChannel")

  def CallMethod(self, method_descriptor, rpc_controller, request, response_class, done):
    """"protol buffer rpc 需要的函数,用来发送rpc调用"""
    self.logger.info('CallMethod')
    cmd_index = method_descriptor.index
    assert(cmd_index < 65535)
    data = request.SerializeToString()
    total_len = len(data) + 2
    self.conn.send_data(''.join([pack('<I', total_len), pack('<H', cmd_index), data]))

  def from_request(self):
    """"从网络解析出一个完整的请求之后调的函数"""
    index_data = self.rpc_request.data[0:2]    
    cmd_index = unpack('<H', index_data)[0]  
    rpc_service = self.rpc_service
    s_descriptor = rpc_service.GetDescriptor()
    method = s_descriptor.methods[cmd_index]  
    try:
      request = rpc_service.GetRequestClass(method)()
      serialized = self.rpc_request.data[2:]    
      request.ParseFromString(serialized)  
      rpc_service.CallMethod(method, self.controller, request, None)
    except:
      self.logger.error("Call rpc method failed!")
      self.logger.log_last_except()
    return True

最后就是继承GameService,并实现connect_server函数了。

class GameService(game_service_pb2.GameService):
  def __init__(self):
    self.logger = LogManager.get_logger("GameService")

  def connect_server(self, rpc_controller, request, callback):
    self.logger.info('%s', request.message)

 至于用于网络收发消息的RpcConnector,可以使用python的asyncore库实现,具体实现在这就不讨论了。

从上面的实现来看,protobuf rpc的实现主要包括编写proto文件并编译生成对应的service_pb2文件,继承RpcChannel并实现CallMethod和调用Service的CallMethod,继承Service来实现暴露给客户端的函数。

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn