可以对照使用google protobuf RPC实现echo service一文看,细节本文不再描述。
google protobuf只负责消息的打包和解包,并不包含RPC的实现,但其包含了RPC的定义。假设有下面的RPC定义:
service MyService {
rpc Echo(EchoReqMsg) returns(EchoRespMsg)
}
那么要实现这个RPC需要最少做哪些事?总结起来需要完成以下几步:
客户端
RPC客户端需要实现google::protobuf::RpcChannel
。主要实现RpcChannel::CallMethod
接口。客户端调用任何一个RPC接口,最终都是调用到CallMethod
。这个函数的典型实现就是将RPC调用参数序列化,然后投递给网络模块进行发送。
void CallMethod(const ::google::protobuf::MethodDescriptor* method,
::google::protobuf::RpcController* controller,
const ::google::protobuf::Message* request,
::google::protobuf::Message* response,
::google::protobuf::Closure* done) {
...
DataBufferOutputStream outputStream(...) // 取决于你使用的网络实现
request->SerializeToZeroCopyStream(&outputStream);
_connection->postData(outputStream.getData(), ...
...
}
服务端
服务端首先需要实现RPC接口,直接实现MyService