代码主要是基于grpc官方examples/cpp/helloworld项目改的, 对helloworld的做了改进,可以方便的增加多个rpc调用接口
关于增加rpc接口的方法做如下介绍:
1. 修改proto文件,增加新接口 如增加新接口 在Greeter里面增加 rpc UploadPlateIn(PlateInRequest) returns (PlateInReply) {}
并增加PlateInRequest 和 PlateInReply数据
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
rpc UploadPlateIn(PlateInRequest) returns (PlateInReply) {}
}
enum PlateType {
TEMPORARY = 0;
MONTHLY_PAYMENT = 1;
OTHER_TYPE = 2;
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
message PlateInRequest {
string plate = 1;
}
message PlateInReply {
string plate = 1;
PlateType plate_type = 2;
}
2. 这里我吧官方例子中greeter_async_server.cc中的CallData改成了模版函数,并且该模版函数继承自CallDataBase接口类(为了暴露接口Proceed() 方便处理不同rpc接口的处理函数的调用)
greeter_async_server.h的代码如下:
#include <memory>
#include <iostream>
#include <string>
#include <thread>
#include <grpcpp/grpcpp.h>
#include <grpc/support/log.h>
#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif
using grpc::Server;
using grpc::ServerAsyncResponseWriter;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCompletionQueue;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;
using helloworld::PlateInRequest;
using helloworld::PlateInReply;
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();
private:
// This can be run in multiple threads if needed.
void HandleRpcs();
std::unique_ptr<ServerCompletionQueue> cq_;
Greeter::AsyncService service_;
std::unique_ptr<Server> server_;
};
class CallDataBase
{
public:
virtual void Proceed() = 0;
virtual ~CallDataBase() {}
};
// Class encompasing the state and logic needed to serve a request.
template<class req, class rep>
class CallData : public CallDataBase
{
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_(