使用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服务的使用。

相关推荐
Cx330❀4 小时前
【Linux网络】网络层协议 IP :从网络层原理到 Linux 内核源码
linux·运维·服务器·网络·tcp/ip·ai·ai编程
FPC工厂——皇榜科技6 小时前
机器人灵巧手线路板:从“握得住”到“摸得准”:一只机械手的柔性神经密码
网络·人工智能·科技·机器人·pcb工艺
Orange_sparkle6 小时前
Pi Agent vs LangGraph:从人机交互、企业 RAG 到持久化工作流的完整选型指南
java·网络·人机交互
xiaoye-duck7 小时前
《Linux 网络编程》深入传输层 UDP 协议原理:端口、报文、缓冲区与内核源码解析
linux·网络·udp
好评1248 小时前
【Linux】数据链路层
linux·运维·网络
天衍四九-8 小时前
第一章:从 LLM 到 Agent —— DeepSeek Harness 入门
网络·数据库·人工智能·python
Jae den8 小时前
网络丢包是什么?
网络
XR1234567889 小时前
医院无线整网高密覆盖选型深度解析
运维·网络
发量惊人的中年网工10 小时前
企业一体化安全网关选型:适用规模、需求架构与实施建议
网络
取啥都被占用10 小时前
两个网络供应商靠树莓派跨个域
网络·树莓派