使用RPC服务的步骤

服务方

1.首先服务的发布方在proto文件里面描述发布的方法,例如发送一个注册方法。

bash 复制代码
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);
}

2.之后protoc user.proto --cpp_out=./生成cpp文件

生成完cpp后加入到服务方的代码中,我们将服务方的类继承于service UserServiceRpc类,重写我们的register类,框架负责调用该方法。

cpp 复制代码
 void Register(::google::protobuf::RpcController* controller,
                       const ::fixbug::RegisterRequest* request,
                       ::fixbug::RegisterResponse* response,
                       ::google::protobuf::Closure* done)
    {
        uint32_t id = request->id();
        std::string name = request->name();
        std::string pwd = request->pwd();

        bool ret = Register(id, name, pwd);

        response->mutable_result()->set_errcode(0);
        response->mutable_result()->set_errmsg("");
        response->set_sucess(ret);

        done->Run();
    }
};

调用方

根据proto文件里发布的方法,来写调用方的代码。

bash 复制代码
int main(int argc, char **argv)
{
    // 整个程序启动以后,想使用mprpc框架来享受rpc服务调用,一定需要先调用框架的初始化函数(只初始化一次)
    MprpcApplication::Init(argc, argv);

    // 演示调用远程发布的rpc方法Register
    fixbug::RegisterRequest req;
    req.set_id(2000);
    req.set_name("mprpc");
    req.set_pwd("666666");
    fixbug::RegisterResponse rsp;

    // 以同步的方式发起rpc调用请求,等待返回结果
    stub.Register(nullptr, &req, &rsp, nullptr); 

    // 一次rpc调用完成,读调用的结果
    if (0 == rsp.result().errcode())
    {
        std::cout << "rpc register response success:" << rsp.sucess() << std::endl;
    }
    else
    {
        std::cout << "rpc register response error : " << rsp.result().errmsg() << std::endl;
    }
    
    return 0;
}

这样就完成了一个服务方和调用方对rpc服务的使用。

相关推荐
looking_for__5 小时前
【Linux】应用层协议
linux·服务器·网络
以太浮标6 小时前
华为eNSP模拟器综合实验之- VLAN终结实践案例分析
网络·计算机网络·华为·智能路由器
Trouvaille ~8 小时前
【Linux】网络编程基础(二):数据封装与网络传输流程
linux·运维·服务器·网络·c++·tcp/ip·通信
柱子jason8 小时前
使用IOT-Tree Server模拟Modbus设备对接西门子PLC S7-200
网络·物联网·自动化·modbus·西门子plc·iot-tree·协议转换
Arvin62710 小时前
研发环境:SSL证书快速部署
网络·网络协议·ssl
Trouvaille ~10 小时前
【Linux】网络编程基础(三):Socket编程预备知识
linux·运维·服务器·网络·c++·socket·网络字节序
酣大智10 小时前
DHCP中继配置实验
运维·网络·网络协议·tcp/ip·华为
小义_10 小时前
【RH134知识点问答题】第6章 管理 SELinux 安全性
linux·网络·云原生·rhel
REDcker11 小时前
RTSP 直播技术详解
linux·服务器·网络·音视频·实时音视频·直播·rtsp
阿猿收手吧!11 小时前
【C++】异常处理:catch块执行后程序如何继续
服务器·网络·c++