1、前言
本文将在滴滴云 DC2 Centos7 环境上,从头搭建 gRPC C++ 开发环境,并运行 gRPC 自带的 C++ 例程。
2、环境准备
2.1 依赖的软件包下载
1 2 3 |
yum install -y gcc gcc-c++ autoconf libtool yum groupinstall -y "Development Tools" |
2.2 下载源码
下载方式如下:
1 2 3 4 |
git clone https://github.com/grpc/grpc.git cd grpc git submodule update --init |
这步需要的时间有点久,特别是网络不好时,访问超时可以重试,已经下载内容不会重新下载,下载后的整个 gRPC 目录大小会超过 1G。
3、编译和安装 Protobuf
3.1 编译和安装
为了方便维护,我们把 Protobuf 和 gRPC 安装在路径 /opt/app
下。gRPC 依赖于 Protobuf,需要先安装 Protobuf:
1 2 3 4 5 6 7 |
cd third_party/protobuf ./autogen.sh mkdir -p /opt/app/protobuf ./configure --prefix=/opt/app/protobuf/ make -j2 make install |
3.2 设置环境变量
在 /etc/profile
文件末尾增加两行:
1 2 3 4 5 |
vi /etc/profile ...... # Protobuf export PATH=$PATH:/opt/app/protobuf/bin |
3.3 检查是否安装好了
加载配置文件 profile,再检查路径是否安装完成:
1 2 3 4 |
source /etc/profile whereis protoc protoc --version |
能正确显示 Protobuf 的版本号就表示已经安装好了。
4、编译和安装 gRPC
4.1 编译和安装
1 2 3 |
cd ../../ mkdir /opt/app/grpc |
搜索当前目录 Makefile 中的一行:
1 2 |
prefix ?= /usr/local |
此行为安装路径,将其改为:
1 2 |
prefix = /opt/app/grpc |
然后执行:
1 2 3 |
make -j2 make install |
4.2 设置环境变量
在 /etc/profile
最后增加下面几行:
1 2 3 4 5 6 7 8 9 10 |
vi /etc/profile ...... # grpc export PATH=$PATH:/opt/app/grpc/bin # 编译grpc例子时Makefile有CPPFLAGS += `pkg-config --cflags protobuf grpc`这行 # 需要依赖PKG_CONFIG_PATH环境变量 export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/opt/app/protobuf/lib/pkgconfig export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/opt/app/grpc/lib/pkgconfig |
4.3 检查是否安装好了
加载配置文件 /etc/profile
,再检查路径并编译 helloworld
例程:
1 2 3 4 5 |
source /etc/profile whereis grpc_cpp_plugin cd examples/cpp/helloworld make |
如果编译没出错,生成的可执行文件中会包含 greeter_server
和 greeter_client
。
执行 greeter_server
发现提示:
1 2 3 |
./greeter_server ./greeter_server: error while loading shared libraries: libprotobuf.so.17: cannot open shared object file: No such file or directory |
原因是 Protobuf 动态链接库路径找不到,我们同时把 Protobuf 和 gRPC 动态库路径加到 /etc/ld.so.conf
配置文件中,增加下面两行:
1 2 3 4 5 |
vi /etc/ld.so.conf ...... /opt/app/protobuf/lib /opt/app/grpc/lib |
再重新加载动态链接库,并运行 greeter_server
和 greeter_client
程序:
1 2 3 4 |
ldconfig ./greeter_server & ./greeter_clien |
输出:“Greeter received: Hello world” 即表示 gRPC C++ 开发环境安装成功了。
本文作者:张杰