目录
1.背景
GRPC 是一个高性能、开源和通用的 RPC 框架,面向服务端和移动端,基于 HTTP/2 设计;
GRPC 默认使用protocol buffers,使用protocol buffers作为IDL和消息交换格式,google开源的成熟的数据序列化机制;
定义服务:通过指定方法调用的参数和返回值来定义,就是使用IDL来 描述你的服务接口和传输消息结构;
gRPC 特点:
①语言中立,支持多种语言;
②基于 IDL 文件定义服务,通过 proto3 工具生成指定语言的数据结构、服务端接口以及客户端 Stub;
③通信协议基于标准的 HTTP/2 设计,支持双向流、消息头压缩、单 TCP 的多路复用、服务端推送等特性,这些特性使得 gRPC 在移动端设备上更加省电和节省网络流量;
④序列化支持 PB(Protocol Buffer)和 JSON,PB 是一种语言无关的高性能序列化框架,基于 HTTP/2 + PB, 保障了 RPC 调用的高性能。

简单理解:Grpc Server 实现方法,Grpc Client 像调用本地方法一样调用server的方法,Server不主动进行通信,主要依靠client调用来进行交互通信;
2.环境配置
开发环境:Linux Qt
grpc源码地址:https://github.com/grpc/grpc/tree/v1.42.0
grpc库文件:需要自己编译或者下载已编译好的库文件即可,这里不做细致讲解。
主要讲解一下protobuf的配置,
安装包地址:https://github.com/protocolbuffers/protobuf/releases

可以根据自己需求进行瞎下载对应的安装包即可,这里我下载的时c++版本;
解压:
unzip protobuf-3.19.1.zip
进入目录:
cd protobuf-3.19.1
配置安装目录:
./config --prefix=/usr/local/protobuf
编译安装:
make
make install
建立链接到bin下:
ln -sf /usr/local/protobuf/bin/protoc /usr/bin/protoc
查看版本号:
protoc --version
3.创建.proto文件并生成对应的pb文件
proto编写:
syntax = "proto3";
package MyGrpcS; //类似于c++ 命名空间
//定义请求信息
message SearchARequest
{
//参数类型 名称 标识号
string request = 1;
int32 statusr = 2;
}
//定义响应信息
message SearchAResponse
{
//参数类型 名称 标识号
string response = 3;
int32 statusr = 4;
}
//同上
message SearchBRequest
{
string request = 5;
int32 statusr = 6;
}
message SearchBResponse
{
string response = 7;
int32 statusr = 8;
}
message StreamRequest
{
int32 mode = 9;
}
message StreamResponse
{
string data = 10;
string type = 11;
int32 num = 12;
}
service SearchService{
//sample rpc
rpc getDataA(SearchARequest) returns (SearchAResponse){}
rpc setDataA(SearchAResponse) returns (SearchARequest){}
rpc getDataB(SearchBRequest) returns (SearchBResponse){}
rpc setDataB(SearchBResponse) returns (SearchBRequest){}
//server rpc
rpc streamData(StreamRequest) returns (stream StreamResponse){}
//client rpc
rpc ctreamData(stream StreamRequest) returns (StreamResponse){}
//server and client rpc
rpc scstreamData(stream StreamRequest) returns (stream StreamResponse){}
}
编译:
protoc --cpp_out=./ GrpcServer.proto
//将生成GrpcServer.pb.cc GrpcServer.pb.h文件
protoc --grpc_out=./ --plugin=protoc-gen-grpc=/home/jiang/ProgramQt/libs/grpc/grpc_cpp_plugin GrpcServer.proto
//将生成GrpcServer.grpc.pb.h GrpcServer.grpc.pb.cc文件
文件如下:

4.代码实现
server端通信需要实现的:
//运行服务器
void runServer(){
std::string server_addr("0.0.0.0:50051");
GrpcServerImp1 service;
ServerBuilder builder;
builder.AddListeningPort(server_addr,grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout<<"server listening on"<<server_addr<<std::endl;
server->Wait();
}
//重载service的虚函数
class GrpcServerImp1 final:public SearchService::Service
{
public:
::grpc::Status getDataA(::grpc::ServerContext* context, con

本文详细介绍gRPC框架的应用,包括环境配置、.proto文件编写、代码实现等步骤,并演示了四种典型的gRPC通信模式。
5842

被折叠的 条评论
为什么被折叠?



