强烈建议有不明白的地方,还是要看官方说明:https://grpc.io/docs/quickstart/cpp/
1.安装
项目代码:https://github.com/grpc/grpc
安装过程说明:https://github.com/grpc/grpc/blob/master/BUILDING.md
yum install build-essential autoconf libtool pkg-config // yum安装nothing to do
git clone https://github.com/grpc/grpc.git
cd grpc
git submodule update --init
make该步不通过
make报错,
解决方法:cd third_party/protobuf/,执行./autogen.sh,编译安装,再到grpc目录执行make
cd third_party/protobuf
sudo ./autogen.sh
sudo ./configure
make
sudo make install
make依然报错:
/usr/lib64/libstdc++.so.6: version GLIBCXX_3.4.18' not found (required by /home/stephen/Documents/tools/grpc/bins/opt/grpc_cpp_plugin) /usr/lib64/libstdc++.so.6: version
CXXABI_1.3.5’ not found (required by /home/stephen/Documents/tools/grpc/bins/opt/grpc_cpp_plugin)
原因:升级gcc版本时,生成的动态库没有替换老版本的动态链接库
解决方法:修改动态链接库,然后make编译通过
$ cp /usr/local/lib64/libstdc++.so.6.0.20 /usr/lib64
$ rm -rf /usr/lib64/libstdc++.so.6
$ ln -s /usr/lib64/libstdc++.so.6.0.20 /usr/lib64/libstdc++.so.6
$ strings /usr/lib64/libstdc++.so.6 | grep GLIBC
具体参考:https://blog.csdn.net/officercat/article/details/39519265
解决后,再次执行make,sudo make install,安装grpc成功
2.安装过程遇到的问题
(1) centos 6.3 git 1.7.1版本太低,升级到2.2
(2) 缺少g++,gcc版本过低,升级gcc版本
下载源码包
$ wget http://file.market.xiaomi.com/download/AppStore/0ba8fa4a47f0f4abb3b0a441ea56451cb2b05fcc8/gcc-4.8.2.tar.gz
解压
tar -zxvf gcc-4.8.2.tar.gz
下载依赖库
$ cd gcc-4.8.2
$ ./contrib/download_prerequisites
configure
$ ./configure --enable-checking=release --enable-languages=c,c++ --disable-multilib
编译
$ make -j4
安装
$ sudo make install
卸载旧版
$ yum erase gcc gcc-c++
2.使用
定义company.proto文件,用protoc编译工具生成相应的代码。
// company.proto文件
syntax = "proto3";
package company; // 表明生成的文件都在namespace company
service Company {
rpc AddEmployee(Employee) returns (EmployeeID) {} // 提交员工信息
rpc ListEmployees(AgeRange) returns (stream Employee) {} // 查询员工信息
}
message Employee {
string name = 1;
int32 age = 2;
}
message EmployeeID {
int32 id = 1;
}
message AgeRange {
int32 low = 1;
int32 high = 2;
}
$ protoc -I protos --grpc_out=cpp --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` protos/company.proto
$ protoc -I protos --cpp_out=cpp protos/company.proto
-I:指定读取的proto文件目录,是--proto_path=protos的简写
--grpc_out:指定生成的grpc文件目录,生成grpc文件需要grpc_cpp_plugin插件
--cpp_out:指定生成的cpp文件目录
读取protos/company.proto文件,分别生成company.grpc.pb.cc、company.grpc.pb.h、company.pb.cc、company.pb.h。
protoc会自动编译生成一些访问的方法,具体参考:https://developers.google.com/protocol-buffers/docs/reference/cpp-generated
cpp_out生成的是proto中定义的message类,grpc_out生成的是proto中定义的service类。
2.1 实现同步grpc
一个client,一个server。
1.server
先来说server,server更清晰。
自动生成操作message和service的方法,需要自己实现server逻辑和启动server服务。
这里用example里hello world说明,greeter_server.cc
class GreeterServiceImpl final : public Greeter::Service {
Status SayHello(ServerContext* context, const HelloRequest* request,
HelloReply* reply) override {
std::string prefix("Hello ");
reply->set_message(prefix + request->name());
return Status::OK;
}
};
void RunServer() {
std::string server_address("0.0.0.0:50051");
GreeterServiceImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
server->Wait();
}
(1)GreeterServiceImpl是实现server的响应逻辑;
(2)通过使用ServerBuilder去构建和启动服务器;
- 创建我们的服务实现类 GreeterServiceImpl 的一个实例;
- 创建工厂类 ServerBuilder 的一个实例;
- 在生成器的 AddListeningPort() 方法中指定客户端请求时监听的地址和端口;
- 用生成器注册我们的服务实现;
- 调用生成器的 BuildAndStart() 方法为我们的服务创建和启动一个RPC服务器;
- 调用服务器的 Wait() 方法实现阻塞等待,直到进程被杀死或者 Shutdown() 被调用;
.
2.client
client为了调用service,需要先创建一个stub,并为client和server创建一个channel,
channel的含义:
A gRPC channel provides a connection to a gRPC server on a specified host and port and is used when creating a client stub (or just “client” in some languages). Clients can specify channel arguments to modify gRPC’s default behaviour, such as switching on and off message compression. A channel has state, including connected and idle.
这里还以helloworld为例子,greeter_client.cc
class GreeterClient {
public:
GreeterClient(std::shared_ptr<Channel> channel)
: stub_(Greeter::NewStub(channel)) {}
};
std::string SayHello(const std::string& user) {
HelloRequest request;
request.set_name(user);
HelloReply reply;
ClientContext context;
// The actual RPC.
Status status = stub_->SayHello(&context, request, &reply);
}
int main(int argc, char** argv) {
// Instantiate the client. It requires a channel, out of which the actual RPCs
// are created. This channel models a connection to an endpoint (in this case,
// localhost at port 50051). We indicate that the channel isn't authenticated
// (use of InsecureChannelCredentials()).
GreeterClient greeter(grpc::CreateChannel(
"localhost:50051", grpc::InsecureChannelCredentials()));
std::string user("world");
std::string reply = greeter.SayHello(user);
std::cout << "Greeter received: " << reply << std::endl;
return 0;
}
(1)先为存根创建一个channel,指定想连接的服务器地址和端口,以及 channel 相关的参数——在本例中我们使用了缺省的 ChannelArguments 并且没有使用SSL;
(2)利用channel创建stub;
(3)通过存根stub发送rpc请求;
- 创建并填充protocol buffer对象HelloRequest;
- 创建protocol buffer对象HelloReply;
- 创建一个 ClientContext 对象——你可以随意的设置该对象上的配置的值,比如期限;
3.编译server和client,开始运行
在examples/cpp/helloworld,make报错:
Package grpc++ was not found in the pkg-config search path.
Perhaps you should add the directory containing `grpc++.pc'
to the PKG_CONFIG_PATH environment variable
No package 'grpc++' found
Package grpc was not found in the pkg-config search path.
Perhaps you should add the directory containing `grpc.pc'
to the PKG_CONFIG_PATH environment variable
意思是找不到环境变量PKG_CONFIG_PATH,解决方法:
在grpc目录下:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export PATH=$PATH:$DIR/bins/opt:$DIR/bins/opt/protobuf
export CPATH=$DIR/include:$DIR/third_party/protobuf/src
export LIBRARY_PATH=$DIR/libs/opt:$DIR/libs/opt/protobuf
export PKG_CONFIG_PATH=$DIR/libs/opt/pkgconfig:$DIR/third_party/protobuf
export LD_LIBRARY_PATH=$DIR/libs/opt
执行:source activate.sh,重新make,报错:
helloworld.pb.h:17:2: error: #error This file was generated by an older version of protoc。
原因是我安装的protoc有两个版本,locate protoc或者find / -name protoc,发现多个版本
创建在/usr/local/bin/目录下创建高版本protoc的软链接。
重新make,代码编译报错,和example里的有一些修改,make编译通过,启动server、client,
启动client报错:
./greeter_client: error while loading shared libraries: libgrpc++.so.1: cannot open shared object file: No such file or directory
原因:greeter_client 动态连接该库时没找到这个库,这个库的搜索目录是在 LD_LIBRARY_PATH环境变量中定义,因此如果没在这个目录中,那么就会找不到,如果已经在这个目录中,可以执行 sudo ldconfig -v 来更新 /etc/ld.so.conf 的 cache(也即 /etc/ld.so.cache 文件)。
参考:
[1] http://senlinzhan.github.io/2017/04/20/grpc/
[2] https://grpc.io/docs/guides/ 介绍what?concepts?authentication?
[3] https://www.jianshu.com/p/efc9167e7044
[4] https://doc.oschina.net/grpc?t=57966 grpc同步异步使用(中文版)
[5] https://www.jianshu.com/p/efc9167e7044