2019独角兽企业重金招聘Python工程师标准>>>

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

一、.proto文件的

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

[cpp] view plain copy

syntax = "proto3";  message SearchRequest
{  string Request = 1;
}  message SearchResponse
{  string Response = 2;
}  service SearchService {  rpc Search (SearchRequest) returns (SearchResponse);
}

二、自动生成代码

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

[cpp] view plain copy

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。

三、服务器代码

[cpp] view plain copy

#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;
}

四、客户端代码

[cpp] view plain copy

#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文件

[cpp] view plain copy

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 搭建完成。

转载于:https://my.oschina.net/u/1426828/blog/1821940

grpc+protobuf 的C++ service 实例解析相关推荐

  1. SoapUI简介和入门实例解析

    SoapUI简介 SoapUI是一个开源测试工具,通过soap/http来检查.调用.实现Web Service的功能/负载/符合性测试.该工具既可作为一个单独的测试软件使用,也可利用插件集成到Ecl ...

  2. Android开发之IPC进程间通信-AIDL介绍及实例解析

    一.IPC进程间通信 IPC是进程间通信方法的统称,Linux IPC包括以下方法,Android的进程间通信主要采用是哪些方法呢? 1. 管道(Pipe)及有名管道(named pipe):管道可用 ...

  3. MVP 模式实例解析

    MVP 模式实例解析 引言 可能有的朋友已经看过我翻译的Jean-Paul Boodhoo的 模型-视图-提供器 模式 一文了(如果没有,建议你先看下再看这篇文章,毕竟这两篇是紧密联系的).在那篇文章 ...

  4. 一个人写一个集群:基于GRPC的golang微服务框架iogo(grpc/protobuf/etcd/freetoo/码客 卢益贵)

    一个人写一个集群:基于GRPC的golang微服务框架iogo keyword:iogo,golang,grpc,protobuf,etcd,zookeeper,microservice,distri ...

  5. Android Service完全解析,关于服务你所需知道的一切(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...

  6. cisco dhcp服务器 修改,思科DHCP服务器配置实例解析

    思科DHCP服务器配置实例解析 首先我们应该汇总下我们所需要达到的目标:为服务器提供固定的地址,即做MAC与IP地址的绑定为客户机提供并非固定的地址,通常这会涉及到子网因为我们的实验环境限制,我们先设 ...

  7. Samba服务器配置(实例解析)

    Samba服务器配置(实例解析) 一.在rhel 8 上配置samba共享服务器 ① 查看samba包信息 [root@localhost ~]# yum info samba #查看samba包信息 ...

  8. 基于net.tcp的WCF配置实例解析

    开通黄钻 基于net.tcp的WCF配置实例解析 本文主要通过文件配置来讲解如何编写一个基于net.tcp的Windows Form小程序. 使用的工具 涉及的工具有: SvcUtil.exe WCF ...

  9. List元素互换,List元素转换下标,Java Collections.swap()方法实例解析

    Java Collections.swap()方法解析 jdk源码: public static void swap(List<?> list, int i, int j) {// ins ...

最新文章

  1. 三目运算符字符串拼接
  2. Java开发语句和代码块模板
  3. Google分布式系统三驾马车: GFS,mapreduce,Bigtable
  4. 在VS中创建多个项目
  5. php curl 批量,PHP实现的curl批量请求操作
  6. Cocos2d-3.x目录介绍分析
  7. Jquery调用ajax参数说明
  8. npm安装vue_零基础入门vue开发
  9. 安全的API接口解决方案
  10. SAS的win10 64位安装过程
  11. linux系统怎么清理磁盘空间,分享5个如何给Ubuntu系统清理磁盘空间、清除垃圾的方法...
  12. java编程语言怎么学习,详细说明
  13. openjdk1.8的下载与安装
  14. unl文件导入orcle数据库
  15. Rclone的介绍和使用
  16. 熵值法与TOPSIS法以及两者结合
  17. draw.io和plantuml替代visio画图工具
  18. HTML中的标记-遁地龙卷风
  19. 信息学竞赛复赛备考策略
  20. android studio 读音,simplicity

热门文章

  1. 测试想要月薪过万?这些能力必不可少!
  2. 一个人学的软件测试,到底有多难?
  3. document api java_GitHub - liuanxin/api-document: java spring-mvc document collect
  4. idea运行springboot出现 Disconnected from the target VM, address: ‘127.0.0.1:xxxx‘, transport: ‘socket‘
  5. python:threading.Thread类的使用详解
  6. mac php memcache扩展,Mac下PHP安装Memcache扩展
  7. PAT甲级1020(附带前中序遍历の绝对干货)
  8. [WARNING] Unable to autodetect 'javac' path, using 'javac' from the environment.
  9. jbig java_jbig2 Java Develop 238万源代码下载- www.pudn.com
  10. java记住用户名和密码_JAVA--高级基础开发Cookie实现记住用户名和密码