目录
先需要通过 proto 文件生成 brpc 框架代码。
protoc --cpp_out <要生成 brpc 代码的路径> <proto 文件路径>
brpc 框架代码代码是以 .pb.h 和 .pb.cc 文件后缀出现的。
服务端代码编写
编写服务端代码时,要先定义一个自己的类,继承 brpc 框架代码中的 EchoService 基类。当服务端收到请求后,EchoService::Echo 成员函数会被调用,所以我们自己的派生类中要对 EchoService::Echo 成员函数进行重写。
EchoService::Echo(::google::protobuf::RpcController* cntl_base,
const ::example::EchoRequest* request,
::example::EchoResponse* response,
::google::protobuf::Closure* done)
{
//...
}
request : 请求,只读的,来自client端的数据包。
response : 回复。需要用户填充,如果存在
required : 字段没有被设置,该次调用会失败。
done : done由框架创建,递给服务回调,包含了调用服务回调后的后续动作,包括检查response正确性,序列化,打包,发送等逻辑。
#include "echo.pb.h"
...
class MyEchoService : public EchoService {
public:
void Echo(::google::protobuf::RpcController* cntl_base,
const ::example::EchoRequest* request,
::example::EchoResponse* response,
::google::protobuf::Closure* done) {
// 这个对象确保在return时自动调用done->Run()
brpc::ClosureGuard done_guard(done);
brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);
// 填写response
response->set_message(request->message());
}
};
在 EchoService::Echo结束时 done->Run() 必须被用户调用一次,而 brpc::ClosureGuard 会像智能指针一样在对象被析构时,调用 done->Run() 。
编写完 EchoService 的派生类后,四步走启动服务进程。
1. 创建服务对象
brpc::Server server;
2. 将 EchoService 的派生类对象添加到服务对象中
MyEchoService echo_service_impl;
if (server.AddService(&echo_service_impl, brpc::SERVER_DOESNT_OWN_SERVICE) != 0)
{
std::cout << "添加服务失败\n";
return -1;
}
3. 给服务对象设置参数,brpc::ServerOptions 类使用来给服务对象设置参数的
brpc::ServerOptions options;
//options.idle_timeout_sec = FLAGS_idle_timeout_s;
//options.num_threads = FLAGS_thread_count;
if (server.Start(12345, &options) != 0)
{
std::cout << "服务启动失败\n";
return -1;
}
4 . 阻塞等待服务端运行
server.RunUntilAskedToQuit();
客户端代码编写
Client指发起请求的一端,在brpc中没有对应的实体,取而代之的是brpc::Channel,它代表和一台或一组服务器的交互通道,Client和Channel在角色上的差别在实践中并不重要,你可以把Channel视作Client。
//创建客户端对象
brpc::Channel channel;
//客户端对象设置参数
brpc::ChannelOptions options;
if(0 != channel.Init("127.0.0.1:12345", nullptr))
{
std::cout << "客户端创建失败\n";
}
example::EchoService_Stub stub(&channel);
// 创建请求、响应、控制对象
example::EchoRequest request;
example::EchoResponse response;
brpc::Controller cntl;
// 构造请求响应
request.set_message("hello world");
stub.Echo(&cntl, &request, &response, NULL);
if (cntl.Failed())
{
std::cout << "请求失败: " << cntl.ErrorText() << std::endl;
return -1;
}
std::cout << "响应:" << response.message() << std::endl;
return 0;