Thrift 安装
Mac 下 Thrift 配置
快速安装
使用 Mac 的包管理器 Homebrew。首先安装 Homebrew:
|
|
使用 Homebrew 安装 thrift:
|
|
如需手动安装特定版本,请参考以下若干小节。
手动安装
首先编译安装 Thrift 的依赖 Boost 和 libevent,接着编译安装 Thrift。
安装 Boost
在 boost.org 下载 boost 库,解压进入文件夹,并通过以下命令编译:
|
|
Boost 库是对 C++ 标准库提供扩展的一些 C++ 程序库的总称。
安装 libevent
在 libevent.org 下载 libevent, 解压并通过如下命令编译安装:
|
|
libevent 是用 C 语言编写的、轻量级开源高性能网络库,基于事件驱动且支持跨平台。
安装 Apache Thrift
下载最新版本的 Apache Thrift,解压并通过如下命令编译安装:
|
|
运行时可能会报错:Bison version 2.5 or higher must be installed on the system!
。参考 How to install bison on mac OSX 解决:
|
|
brew link bison
是在系统路径下添加 bison 的 symlinks。在装完 thrift 之后记得:
|
|
Ubuntu 下 Thrift 配置
参考链接
[1] Debian/Ubuntu install
[2] Building from source
[3] Apache Thrift Tutorial
安装依赖
执行命令:
|
|
安装 Thrift
在 Thrift 官网 下载最新的打包文件,解压后进入文件夹,输入如下命令编译安装:
|
|
Thrift C++ 实例
本节中我们实现一个简单的加减乘除计算器 C/S 实例。
基本过程
- 编写接口描述文件 calculator.thrift,定义数据类型和服务接口
- 编译 calculator.thrift 生成 gen-cpp 源代码文件夹
- 编写 server 代码,引用 gen-cpp 与 thrift 库目录编译
- 编写 client 代码,引用 gen-cpp 与 thrift 库目录编译
- 运行 ./server
- 运行 ./client
Thrift 脚本
假设服务端(Server)为客户端(Client)提供简单的数学运算功能,编写 calculator.thrift 脚本文件如下:
|
|
编译 Thrift 脚本的基本命令格式为:
|
|
如果在一个 .thrift 文件里包含了其他的 .thrift 文件,需要递归编译,执行:
|
|
本例中,我们执行如下命令编译:
|
|
在当前目录下会生成一个 gen-cpp 文件夹。文件夹里包含 MathService.h/cpp, calculator_constants.h/cpp, calculator_types.h/cpp 和 MathService_server.skeleton.cpp 7 个文件。前 6 个文件用于接口定义,需要同时被 Client 和 Server 代码引用(调用或实现),而 MathService_server.skeleton.cpp 则提供了 Server 端代码的一个基本框架。
Server 程序
新建 calculator 文件夹,把 gen-cpp 复制进去,并将 gen-cpp 里的 MathService_server.skeleton.cpp 重命名为 server.cpp,移动到 server 文件夹。实现 server.cpp 后的完整代码如下:
|
|
Client 程序
在 calculator 文件夹里新建 client.cpp 文件,代码如下:
|
|
编译
用 g++ 编译,先针对各个 .cpp 文件生成 .o 目标,然后链接 thrift 库,生成可执行文件 client 和 server。由于 thrift 里用到 c++11 里的 bind 方法,需要指定 -std=c++11
。假设 thrift 库安装在 /usr/local/lib 里,thrift 的头文件在 /usr/local/include/thrift 中,则完整的编译命令如下:
|
|
可以直接执行以上命令,也可以将以上命令写进一个 build.sh 文件里,然后执行:
|
|
生成完 client 和 server 后,分别在两个终端执行 ./server
和 ./client
,可以分别看到 Start server...
和 1 + 1 = 2 ...
。
综上。
Thrift 脚本语法
Thrift 用于跨语言的 RPC 通信,因此其接口定义文件 *.thrift
中包含的数据结构与函数定义必须对于不同语言都适用。官网的 Thrift Wiki Tutorial 基本包含了所有的 Thrift 语法,无须赘述,这里只是把它复制过来:
|
|
参考链接
[1] Apache Thrift OS X Setup
[2] mac os x10.10 安装thrift
[3] Thrift C++ Tutorial