grpc+protobuf 的C++ service 生成pb.cc,pb.h实例解析

这篇文章将会简单的描述一下grpc+protobuf 的C++ service的搭建过程,告诉读者在linux系统下怎样实现一个service接口的流程。

一、.proto文件的

实现一个简单的helloworld回显功能,首先需要一个.proto文件,我将它命名为example.proto,文件内容如下:

  1. syntax = "proto3";  
  2.   
  3. message SearchRequest  
  4. {  
  5.     string Request = 1;  
  6. }  
  7.   
  8. message SearchResponse  
  9. {  
  10.     string Response = 2;  
  11. }  
  12.   
  13. service SearchService {  
  14.         rpc Search (SearchRequest) returns (SearchResponse);  
  15. }  
	syntax = "proto3";

	message SearchRequest
	{
		string Request = 1;
	}

	message SearchResponse
	{
		string Response = 2;
	}

	service SearchService {
  		rpc Search (SearchRequest) returns (SearchResponse);
	}

二、自动生成代码

使用example.proto文件自动生成grpc和protobuf的代码

  1. protoc --cpp_out=./ examples.proto  
  2. protoc --grpc_out=./ --plugin=protoc-gen-grpc=/usr/local/bin/grpc_cpp_plugin examples.proto  
protoc --cpp_out=./ examples.proto
protoc --grpc_out=./ --plugin=protoc-gen-grpc=/usr/local/bin/grpc_cpp_plugin examples.proto
这两个命令将会生成四个文件, examples.grpc.pb.cc、examples.grpc.pb.h、examples.pb.cc、examples.pb.h。

三、服务器代码

  1. #include <iostream>  
  2. #include <memory>  
  3. #include <string>  
  4.   
  5. #include <grpc++/grpc++.h>  
  6. #include <grpc/grpc.h>  
  7. #include <grpc++/server.h>  
  8. #include <grpc++/server_builder.h>  
  9. #include <grpc++/server_context.h>  
  10.   
  11. #include "examples.grpc.pb.h"  
  12.   
  13. using grpc::Server;  
  14. using grpc::ServerBuilder;  
  15. using grpc::ServerContext;  
  16. using grpc::Status;  
  17.   
  18. class SearchRequestImpl final : public SearchService::Service {  
  19.   Status Search(ServerContext* context, const SearchRequest* request,  
  20.                   SearchResponse* reply) override {  
  21.     std::string prefix("Hello ");  
  22.     reply->set_response(prefix + request->request());  
  23.     return Status::OK;  
  24.   }  
  25. };  
  26.   
  27. void RunServer() {  
  28.   std::string server_address("0.0.0.0:50051");  
  29.   SearchRequestImpl service;  
  30.   
  31.   ServerBuilder builder;  
  32.   builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());  
  33.   builder.RegisterService(&service);  
  34.   std::unique_ptr<Server> server(builder.BuildAndStart());  
  35.   std::cout << "Server listening on " << server_address << std::endl;  
  36.   
  37.   server->Wait();  
  38. }  
  39.   
  40. int main(int argc, char** argv) {  
  41.   RunServer();  
  42.   
  43.   return 0;  
  44. }  
#include <iostream>
#include <memory>
#include <string>

#include <grpc++/grpc++.h>
#include <grpc/grpc.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>

#include "examples.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;

class SearchRequestImpl final : public SearchService::Service {
  Status Search(ServerContext* context, const SearchRequest* request,
                  SearchResponse* reply) override {
    std::string prefix("Hello ");
    reply->set_response(prefix + request->request());
    return Status::OK;
  }
};

void RunServer() {
  std::string server_address("0.0.0.0:50051");
  SearchRequestImpl service;

  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;

  server->Wait();
}

int main(int argc, char** argv) {
  RunServer();

  return 0;
}

四、客户端代码

  1. #include <iostream>  
  2. #include <memory>  
  3. #include <string>  
  4.   
  5. #include <grpc++/grpc++.h>  
  6. #include <grpc/support/log.h>  
  7.   
  8. #include "examples.grpc.pb.h"  
  9.   
  10. using grpc::Channel;  
  11. using grpc::ClientAsyncResponseReader;  
  12. using grpc::ClientContext;  
  13. using grpc::CompletionQueue;  
  14. using grpc::Status;  
  15.   
  16.   
  17. class ExampleClient {  
  18.  public:  
  19.   explicit ExampleClient(std::shared_ptr<Channel> channel)  
  20.       : stub_(SearchService::NewStub(channel)) {}  
  21.    
  22.   std::string Search(const std::string& user) {  
  23.    
  24.     SearchRequest request;  
  25.     request.set_request(user);  
  26.    
  27.     SearchResponse reply;  
  28.      
  29.     ClientContext context;  
  30.   
  31.     CompletionQueue cq;  
  32.   
  33.     Status status;  
  34.   
  35.     std::unique_ptr<ClientAsyncResponseReader<SearchResponse> > rpc(  
  36.         stub_->AsyncSearch(&context, request, &cq));  
  37.   
  38.     rpc->Finish(&reply, &status, (void*)1);  
  39.     void* got_tag;  
  40.     bool ok = false;  
  41.     
  42.     GPR_ASSERT(cq.Next(&got_tag, &ok));  
  43.   
  44.      
  45.     GPR_ASSERT(got_tag == (void*)1);  
  46.     
  47.     GPR_ASSERT(ok);  
  48.   
  49.     if (status.ok()) {  
  50.       return reply.response();  
  51.     } else {  
  52.       return "RPC failed";  
  53.     }  
  54.   }  
  55.   
  56.  private:  
  57.    
  58.   std::unique_ptr<SearchService::Stub> stub_;  
  59. };  
  60.   
  61. int main(int argc, char** argv) {  
  62.   ExampleClient client(grpc::CreateChannel(  
  63.       "localhost:50051", grpc::InsecureChannelCredentials()));  
  64.   std::string user("world");  
  65.   std::string reply = client.Search(user);  // The actual RPC call!  
  66.   std::cout << "client received: " << reply << std::endl;  
  67.   
  68.   return 0;  
  69. }  
#include <iostream>
#include <memory>
#include <string>

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

#include "examples.grpc.pb.h"

using grpc::Channel;
using grpc::ClientAsyncResponseReader;
using grpc::ClientContext;
using grpc::CompletionQueue;
using grpc::Status;


class ExampleClient {
 public:
  explicit ExampleClient(std::shared_ptr<Channel> channel)
      : stub_(SearchService::NewStub(channel)) {}
 
  std::string Search(const std::string& user) {
 
    SearchRequest request;
    request.set_request(user);
 
    SearchResponse reply;
   
    ClientContext context;

    CompletionQueue cq;

    Status status;

    std::unique_ptr<ClientAsyncResponseReader<SearchResponse> > rpc(
        stub_->AsyncSearch(&context, request, &cq));

    rpc->Finish(&reply, &status, (void*)1);
    void* got_tag;
    bool ok = false;
  
    GPR_ASSERT(cq.Next(&got_tag, &ok));

   
    GPR_ASSERT(got_tag == (void*)1);
  
    GPR_ASSERT(ok);

    if (status.ok()) {
      return reply.response();
    } else {
      return "RPC failed";
    }
  }

 private:
 
  std::unique_ptr<SearchService::Stub> stub_;
};

int main(int argc, char** argv) {
  ExampleClient client(grpc::CreateChannel(
      "localhost:50051", grpc::InsecureChannelCredentials()));
  std::string user("world");
  std::string reply = client.Search(user);  // The actual RPC call!
  std::cout << "client received: " << reply << std::endl;

  return 0;
}

五、Makefile文件


  1. subdir = ./  
  2.   
  3. export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig  
  4.   
  5. SOURCES = $(wildcard $(subdir)*.cc)  
  6. SRCOBJS = $(patsubst %.cc,%.o,$(SOURCES))  
  7. CC = g++  
  8.   
  9. %.o:%.cc  
  10.     $(CC) -std=c++11 -I/usr/local/include -pthread -c $< -o $@  
  11.   
  12. all: client server  
  13.   
  14. client: examples.grpc.pb.o examples.pb.o examples_client.o  
  15.     $(CC) $^ -L/usr/local/lib `pkg-config --libs grpc++ grpc` -Wl,--no-as-needed -lgrpc++_reflection -Wl,--as-needed -lprotobuf -lpthread -ldl -lssl -o $@  
  16.   
  17. server: examples.grpc.pb.o examples.pb.o examples_server.o  
  18.     $(CC) $^ -L/usr/local/lib `pkg-config --libs grpc++ grpc` -Wl,--no-as-needed -lgrpc++_reflection -Wl,--as-needed -lprotobuf -lpthread -ldl -lssl -o $@  
  19. #chmod 777 $@  
  20.   
  21. clean:  
  22.     sudo rm *.o  
subdir = ./

export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

SOURCES = $(wildcard $(subdir)*.cc)
SRCOBJS = $(patsubst %.cc,%.o,$(SOURCES))
CC = g++

%.o:%.cc
	$(CC) -std=c++11 -I/usr/local/include -pthread -c $< -o $@

all: client server

client:	examples.grpc.pb.o examples.pb.o examples_client.o
	$(CC) $^ -L/usr/local/lib `pkg-config --libs grpc++ grpc` -Wl,--no-as-needed -lgrpc++_reflection -Wl,--as-needed -lprotobuf -lpthread -ldl -lssl -o $@

server:	examples.grpc.pb.o examples.pb.o examples_server.o
	$(CC) $^ -L/usr/local/lib `pkg-config --libs grpc++ grpc` -Wl,--no-as-needed -lgrpc++_reflection -Wl,--as-needed -lprotobuf -lpthread -ldl -lssl -o $@
#chmod 777 $@

clean:
	sudo rm *.o



六、运行

运行./server启动service,在另一个端口运行./client 打印出:client received: Hello world表示两边已通,grpc+protobuf 搭建完成。


  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
注:下文中的 *** 代表文件名中的组件名称。 # 包含: 中文-英文对照文档:【***-javadoc-API文档-中文(简体)-英语-对照版.zip】 jar包下载地址:【***.jar下载地址(官方地址+国内镜像地址).txt】 Maven依赖:【***.jar Maven依赖信息(可用于项目pom.xml).txt】 Gradle依赖:【***.jar Gradle依赖信息(可用于项目build.gradle).txt】 源代码下载地址:【***-sources.jar下载地址(官方地址+国内镜像地址).txt】 # 本文件关键字: 中文-英文对照文档,中英对照文档,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册 # 使用方法: 解压 【***.jar中文文档.zip】,再解压其中的 【***-javadoc-API文档-中文(简体)版.zip】,双击 【index.html】 文件,即可用浏览器打开、进行查看。 # 特殊说明: ·本文档为人性化翻译,精心制作,请放心使用。 ·本文档为双语同时展示,一行原文、一行译文,可逐行对照,避免了原文/译文来回切换的麻烦; ·有原文可参照,不再担心翻译偏差误导; ·边学技术、边学英语。 ·只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; ·不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 # 温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件;

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值