微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在微服务 C++

如何解决在微服务 C++

我是使用 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/ 是最好的起点。使用异步的 helloworld 示例 (https://github.com/grpc/grpc/tree/v1.35.0/examples/cpp/helloworld) 也是一个很好的参考。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。