在使用rpc服务时,首先,需要由proto文件,来知道我可以调用哪些远程接口。proto文件和服务方都能看到。这也是protobuf的使用优势。
syntax = "proto3";
package fixbug;
option cc_generic_services = true;
message ResultCode
{
int32 errcode = 1;
bytes errmsg = 2;
}
message LoginRequest
{
bytes name = 1;
bytes pwd = 2;
}
message LoginResponse
{
ResultCode result = 1;
bool sucess = 2;
}
message RegisterRequest
{
uint32 id = 1;
bytes name = 2;
bytes pwd = 3;
}
message RegisterResponse
{
ResultCode result = 1;
bool sucess = 2;
}
service UserServiceRpc
{
rpc Login(LoginRequest) returns(LoginResponse);
rpc Register(RegisterRequest) returns(RegisterResponse);
}
protobuf允许我们使用 fixbug::UserServiceRpc_Stub stub(new MprpcChannel()),来调用rpc的服务方法。其中stub对象需要通过channel构造,在调用login函数时,会进入到callmethod方法。我们可以重写channel的callmethod方法来处理将login里面的参数序列化发送到服务的提供方。
int main(int argc, char **argv)
{
// 整个程序启动以后,想使用mprpc框架来享受rpc服务调用,一定需要先调用框架的初始化函数(只初始化一次)
MprpcApplication::Init(argc, argv);
// 演示调用远程发布的rpc方法Login
fixbug::UserServiceRpc_Stub stub(new MprpcChannel());
// rpc方法的请求参数
fixbug::LoginRequest request;
request.set_name("zhang san");
request.set_pwd("123456");
// rpc方法的响应
fixbug::LoginResponse response;
// 发起rpc方法的调用 同步的rpc调用过程 MprpcChannel::callmethod
stub.Login(nullptr, &request, &response, nullptr); // RpcChannel->RpcChannel::callMethod 集中来做所有rpc方法调用的参数序列化和网络发送
// 一次rpc调用完成,读调用的结果
if (0 == response.result().errcode())
{
std::cout << "rpc login response success:" << response.sucess() << std::endl;
}
else
{
std::cout << "rpc login response error : " << response.result().errmsg() << std::endl;
}