grpc 报错 At least one of the completion queues must be frequently polled 如何改进, 给出cpp代码
时间: 2024-03-06 20:49:14 浏览: 266
以下是一个简单的gRPC服务器示例代码(C++),其中包含了正确处理CQ的示例:
```cpp
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "my_service.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using my_service::Request;
using my_service::Response;
using my_service::MyService;
class MyServiceImpl final : public MyService::Service {
Status MyMethod(ServerContext* context, const Request* request,
Response* response) override {
// Handle request
return Status::OK;
}
};
void RunServer() {
std::string server_address("0.0.0.0:50051");
MyServiceImpl service;
grpc::EnableDefaultHealthCheckService(true);
grpc::reflection::InitProtoReflectionServerBuilderPlugin();
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
while (true) {
// Poll CQs frequently
server->GetCompletionQueue()->Next();
}
}
int main(int argc, char** argv) {
RunServer();
return 0;
}
```
在上面的代码中,我们使用了gRPC提供的`GetCompletionQueue()`方法来获取CQ,并在无限循环中调用其`Next()`方法来处理异步操作完成时的通知。这样可以确保及时处理异步操作完成时的通知,从而避免了"At least one of the completion queues must be frequently polled"错误的发生。
此外,我们还使用了gRPC提供的`EnableDefaultHealthCheckService()`和`reflection::InitProtoReflectionServerBuilderPlugin()`方法来启用默认健康检查服务和Proto Reflection服务,以提高服务器的可靠性和稳定性。
阅读全文