gRPC:RPC处理程序如何正确检测`Server`是否为`Shutdown()`

siv*_*udh 4 c++ qt grpc

目前,我正在使用一种hackish方式 - 一个全局变量 - 使RPC处理程序能够检测到Server已经(即将被)调用Shutdown().

bool g_ServerIsNotDead = true;   // Hack!

Status StreamServiceImpl::GetCurrentTemperature(ServerContext *context_,
                                                const UpdateInterval *request_,
                                                ServerWriter<Temperature> *stream_)
{
  auto currentTemp = 100.0f;
  while(g_ServerIsNotDead)   // Hack!!!
  {
    qDebug() << QThread::currentThreadId() << currentTemp << "farenheit.";

    Temperature message;
    message.set_temperature(currentTemp);
    stream_->Write(message);

    QThread::sleep(2);

    currentTemp += 1.0f;
  }

  return Status::OK;
}

void insideSomeFunction() {
   // Testing shutdown 5 seconds later
   QTimer::singleShot(std::chrono::seconds(5), this, [=]() {
      qDebug() << "Shuting down!";

      g_ServerIsNotDead = false;   // Hack!!

      this->server->Shutdown();    // This method actually blocks until all RPC handlers have exited, believe it or not!

      emit shutdown();

      qDebug() << "All dead.";
  });
}
Run Code Online (Sandbox Code Playgroud)

参考:https://github.com/C0D1UM/grpc-qt-example/blob/master/rpc_server/hellostream_server.cpp

这将是非常好的,如果我能以某种方式检查Server已经Shutdown()grpc::ServerContext,但我没有看到任何相关的方法来实现这一目标.

如果有人可以提出一种方法来完全取出while循环(?),那就更好了.我正在使用Qt所以一切都是事件驱动的.

小智 5

所以,我认为值得明确的是什么Shutdown.有关于此详细评论,但基本上,服务器Shutdown不会失败,取消或终止您现有的正在进行的调用(除非您使用截止日期参数和gRPC C++异步API).

相反,它停止侦听新连接,停止接受新呼叫,未通过请求但尚未接受的呼叫.如果您想在关机时失败或终止呼叫,您可以像上面那样在应用级代码上执行此操作.

我建议您不要使用全局变量,而应使用类的成员函数,StreamServiceImpl以便在您选择时可以支持在同一进程中运行的多个服务.