在微服务c++中运行gRPC服务器



我是一个使用gRPC的新手。我正在创建一个需要运行长计算并通过gRPC将结果返回给客户端的微服务。我正在努力弄清楚如何在一个或多个线程中运行gRPC服务器,并在另一个线程中进行计算。

通常您会希望服务器实例运行,并且在请求进入时进行一些数据检索或一些计算,然后制定结果并将其返回给请求者。在许多情况下,执行的操作不重要,可能需要时间来处理。理想情况下,您不希望服务器线程阻塞等待操作完成。我发现的c++代码示例相当琐碎,并且正在寻找有关如何正确实现此场景的更多指导。

控制器看起来像这样:

void dummyFunction() {
while(true) {
// do something
}
}
void start() {

thread main_thread = thread{dummyFunction};
main_thread.join();
...
mainGRPCServer->start(target_str);
}

在MainServer实现中,我使用了与greeter示例相同的同步服务器


void RunServer(string &server_address) {
NServiceImpl n_service;
SServiceImpl s_service;
grpc::EnableDefaultHealthCheckService(true);
grpc::reflection::InitProtoReflectionServerBuilderPlugin();
ServerBuilder builder;
// Listen on the given address without any authentication mechanism.
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
// Register "service" as the instance through which we'll communicate with
// clients. In this case it corresponds to an *synchronous* service.
builder.RegisterService(&n_service);
builder.RegisterService(&s_service);
// Finally assemble the server.
std::unique_ptr<Server> server(builder.BuildAndStart());
// Wait for the server to shutdown. Note that some other thread must be
// responsible for shutting down the server for this call to ever return.
server->Wait();
}
void MainServerImpl::start(string & target_str) {
worker_ = thread( RunServer, ref(target_str));
worker_.join();
}

显然这个实现是不会工作的,因为我理解grpc服务器本身有它自己的线程模型。我研究了使用async服务器实现。谁能指导我如何构建这个?

更新:我在GoogleGroups上发现了这个:*The C++ server has two threading models available: sync and async. Most users will want to use the sync model: the server will have an (internal) threadpool that manages multiplexing requests onto some number of threads (reusing threads between requests). The async model allows you to bring your own threading model, but is a little trickier to use - in that mode you request new calls when your server is ready for them, and block in completion queues while there is no work to do. By arranging when you block on the completion queues, and on which completion queues you make requests, you can arrange a wide variety of threading models.*

但是我似乎仍然找不到任何好的实现例子

目前找到的最好的介绍是https://grpc.io/docs/languages/cpp/async/

是的,https://grpc.io/docs/languages/cpp/async/是最好的起点。使用async的helloworld示例(https://github.com/grpc/grpc/tree/v1.35.0/examples/cpp/helloworld)也是一个很好的参考。

最新更新