c++客户端 grpc,如何从客户端关闭gRPC服务器(使用RPC功能)

I'm using gRPC for inter-process communication between C++ App (gRPC Server) and Java App (gRPC Client). Everything run on one machine. I want to provide client possibility to shut down the server. My idea is to add RPC function to service in proto which would do it.

The C++ Implementation would be:

class Service : public grpcGeneratedService

{

public:

......

private:

grpc::Server* m_pServer;

};

grpc::Status Service::ShutDown(grpc::ServerContext* pContext, const ShutDownRequest* pRequest, ShutDownResponse* pResponse)

{

if (m_pServer)

m_pServer->Shutdown();

return grpc::Status(grpc::StatusCode::OK, "");

}

However the ShutDown blocks until all RPC calls are processed what means dead-lock. Is there any elegant way how to implement it?

解决方案

I'm using a std::promise with a method almost exactly like yours.

// Somewhere in the global scope :/

std::promise exit_requested;

// My method looks nearly identical to yours

Status CoreServiceImpl::shutdown(ServerContext *context, const SystemRequest *request, Empty*)

{

LOG(INFO) << context->peer() << " - Shutdown request acknowledged.";

exit_requested.set_value();

return Status::OK;

}

In order to make this work, I call server->Wait() in a second thread and wait on the future for the exit_requested promise to block a shutdown call:

auto serveFn = [&]() {

server->Wait();

};

std::thread serving_thread(serveFn);

auto f = exit_requested.get_future();

f.wait();

server->Shutdown();

serving_thread.join();

Once I had this I was also able to support a clean shutdown via signal handlers as well:

auto handler = [](int s) {

exit_requested.set_value();

};

std::signal(SIGINT, handler);

std::signal(SIGTERM, handler);

std::signal(SIGQUIT, handler);

I've been satisfied with this approach so far and it's kept me within the bounds of gRPC and the standard c++ libs. Rather than use some globally scoped promise (I have to declare it as an external in my service implementation source) I should probably think of something more elegant.

One thing to note here is that setting the value of the promise more than once will throw an exception. This could happen if you somehow send the shutdown message and also pkill -2 my_awesome_service at the same time. I actually ran into this when there was a deadlock in my persistence layer preventing shutdown from finishing, when I tried to send a SIGINT again the service aborted instead! For my needs this is still an acceptable solution but I'd love to hear about alternatives that work around or solve that little problem.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值