grpc c++ async server 源码解读

#include <memory>
#include <iostream>
#include <string>
#include <thread>

#include <grpcpp/grpcpp.h>
#include <grpc/support/log.h>

#include "helloworld.grpc.pb.h"

// 异步回复写
using grpc::ServerAsyncResponseWriter;
// 服务器完成队列
using grpc::ServerCompletionQueue;

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;

// 异步服务器
class ServerImpl final {
 public:
  ~ServerImpl() {
    server_->Shutdown();
    // Always shutdown the completion queue after the server.
    // 总是在 服务器之后 关闭 完成队列
    cq_->Shutdown();
  }

  // There is no shutdown handling in this code.
  void Run() {
    std::string server_address("0.0.0.0:50051");

    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 *asynchronous* service.
    builder.RegisterService(&service_);
    // Get hold of the completion queue used for the asynchronous communication
    // with the gRPC runtime.
    // completion queue 完成队列
    cq_ = builder.AddCompletionQueue();
    // Finally assemble the server.
    server_ = builder.BuildAndStart();
    std::cout << "Server listening on " << server_address << std::endl;

    // Proceed to the server's main loop.
    HandleRpcs();
  }

 private:
  // Class encompasing the state and logic needed to serve a request.
  // 嵌套类
  class CallData {
   public:
    // Take in the "service" instance (in this case representing an asynchronous
    // server) and the completion queue "cq" used for asynchronous communication
    // with the gRPC runtime.
    CallData(Greeter::AsyncService* service, ServerCompletionQueue* cq)
        : service_(service), cq_(cq), responder_(&ctx_), status_(CREATE) {
      // Invoke the serving logic right away.
      Proceed();
    }

    void Proceed() {
      if (status_ == CREATE) {
        // Make this instance progress to the PROCESS state.
        status_ = PROCESS;
        // 作为初始化 CREATE 状态的一部分,我们请求system 去开始处理 SayHello 请求。
        // this 表示 CallData 实例的地址 唯一的标志了 request 请求,所以不同的 CallData 实例可以并行的
        // As part of the initial CREATE state, we *request* that the system
        // start processing SayHello requests. In this request, "this" acts are
        // the tag uniquely identifying the request (so that different CallData
        // instances can serve different requests concurrently), in this case
        // the memory address of this CallData instance.
        service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
                                  this);
      } else if (status_ == PROCESS) {
        // Spawn a new CallData instance to serve new clients while we process
        // the one for this CallData. The instance will deallocate itself as
        // part of its FINISH state.
        new CallData(service_, cq_);
        std::string prefix("hello\n");
        // The actual processing.
        reply_.set_message(prefix + request_.name());

        // And we are done! Let the gRPC runtime know we've finished, using the
        // memory address of this instance as the uniquely identifying tag for
        // the event.
        status_ = FINISH;
        responder_.Finish(reply_, Status::OK, this);
      } else {
        GPR_ASSERT(status_ == FINISH);
        // Once in the FINISH state, deallocate ourselves (CallData).
        // 一旦进入了 finish 状态,析构自身
        delete this;
      }
    }

   private:
    // The means of communication with the gRPC runtime for an asynchronous
    // server.
    // 异步服务
    Greeter::AsyncService* service_;
    // The producer-consumer queue where for asynchronous server notifications.
    // 完成队列
    ServerCompletionQueue* cq_;
    // Context for the rpc, allowing to tweak aspects of it such as the use
    // of compression, authentication, as well as to send metadata back to the
    // client.
    // 服务器上下文
    ServerContext ctx_;

    // What we get from the client.
    HelloRequest request_;
    // What we send back to the client.
    HelloReply reply_;

    // The means to get back to the client.
    // 服务器异步回复写
    ServerAsyncResponseWriter<HelloReply> responder_;

    // Let's implement a tiny state machine with the following states.
    enum CallStatus { CREATE, PROCESS, FINISH };
    CallStatus status_;  // The current serving state.
  };

  // This can be run in multiple threads if needed.
  // 可以在多线程中运行
  void HandleRpcs() {
    // Spawn a new CallData instance to serve new clients.
    // 孵化一个新的 CallData 实例 去服务 new clients
    new CallData(&service_, cq_.get());
    void* tag;  // uniquely identifies a request. 唯一的标记一个 request
    bool ok;
    while (true) {
      // Block waiting to read the next event from the completion queue. The
      // event is uniquely identified by its tag, which in this case is the
      // memory address of a CallData instance.
      // 在这里 tag 是 CallData 实例的内存地址
      // The return value of Next should always be checked. This return value
      // tells us whether there is any kind of event or cq_ is shutting down.
      GPR_ASSERT(cq_->Next(&tag, &ok));
      GPR_ASSERT(ok);
      static_cast<CallData *>(tag)->Proceed();
      // static_cast<CallData*>(tag)->Proceed();
    }
  }

  // 完成队列
  std::unique_ptr<ServerCompletionQueue> cq_;
  // 异步服务器
  Greeter::AsyncService service_;
  // Server 服务器
  std::unique_ptr<Server> server_;
};

int main(int argc, char** argv) {
  ServerImpl server;
  server.Run();
  return 0;
}

解析

该服务主要运行流程为
main 函数中创建了一个 ServerImpl 实例,运行 Run() 函数。
Run() 函数中使用一个 ServerBuilder 绑定服务端口号,注册服务为Greeter::AsyncService 实例。builder.BuildAndStart() 返回一个唯一智能指针,用于析构函数中对 Server 的清除。
HandleRpcs() 函数开始服务器真正的数据处理循环(Proceed to the server’s main loop.)
class CallData 的私有变量如下

 	Greeter::AsyncService* service_;
    ServerCompletionQueue* cq_;
    
    ServerContext ctx_;
    ServerAsyncResponseWriter<HelloReply> responder_;

    HelloRequest request_;
    HelloReply reply_;
    enum CallStatus { CREATE, PROCESS, FINISH };
    CallStatus status_;  // The current serving state.

其中 service_ , cq_ 外部传入。
ServerAsyncResponseWriter<HelloReply> 作为服务器异步回复写,ServerContext是rpc服务器必须使用的上下文。

我们唯一需要详细了解的就是

service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,this);

该函数请求system 处理 SayHello 的请求,并且提示队列设置为 cq_。这样我们在使用cq_->Next()时阻塞,当cq_中有新的request时便会触发。需要注意的是CallData 的创建以及Proceed()函数,在新建一个CallData时便会触发一此Create状态的Proceed()。在处理的过程中会new 一个新的CallData用于下一个请求的处理。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40021744/article/details/86760547