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

标签 c++ multithreading c++17 grpc

我是使用gRPC的相对新手。我正在创建一个微服务,该微服务需要运行长时间的计算并将结果通过gRPC返回给客户端。我正在尝试弄清如何在一个或多个线程中运行gRPC服务器,以及如何在另一个线程中运行计算。
通常,您希望服务器实例正在运行,并且在请求进入时进行一些数据检索或某些计算,然后制定结果并将其返回给请求者。在许多情况下,操作并非平凡,可能需要花费一些时间来处理。理想情况下,您不希望服务器线程阻塞以等待操作完成。我发现的C++代码示例相当琐碎,并且正在寻找有关如何正确实现此方案的更多指导。
Controller 看起来像这样:

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 Server本身具有自己的线程模型,因此该实现无法正常工作。我看过使用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/是最好的起点。使用异步的helloworld示例(https://github.com/grpc/grpc/tree/v1.35.0/examples/cpp/helloworld)也将是一个很好的引用。

关于c++ - 在微服务C++中运行gRPC服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65917252/

相关文章:

c++ - 为什么 is_class<T> 在此代码段中不起作用?

c++ - 这个条件如何成立

c++ - 在 Qt 中生成(模拟)假鼠标事件

java - 每个请求模型的线程能否比非阻塞 I/O 更快?

c++ - 模板类中的模板成员函数特化

c++ - 设置使用 libHaru 生成的 PDF 的背景颜色

C# 等待任务组,但返回对象

ruby-on-rails - 如何捕获模型回调中不同线程上引发的 rsolr Sunspot 异常?

c++ - 使用花括号而不是括号时 Visual Studio 会中断

c++ - 具有类型删除的 AnyFunction 类