Thrift 安装
Mac 下 Thrift 安装
快速安装
使用 Mac 的包管理器 Homebrew。首先安装 Homebrew:
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
使用 Homebrew 安装 thrift:
brew install thrift
如需手动安装特定版本,请参考以下若干小节。
手动安装
首先编译安装 Thrift 的依赖 Boost 和 libevent,然后编译安装 Thrift。
安装 Boost
在 boost.org 下载 boost 库,解压进入文件夹,并通过以下命令编译:
./bootstrap.sh
sudo ./b2 threading=multi address-model=64 variant=release stage install
Boost 库是对 C++ 标准库提供扩展的一些 C++ 程序库的总称。
安装 libevent
在 libevent.org 下载 libevent, 解压并通过如下命令编译安装:
./configure --prefix=/usr/local
make
sudo make install
libevent 是用 C 语言编写的、轻量级开源高性能网络库,基于事件驱动且支持跨平台。
安装 Apache Thrift
下载最新版本的 Apache Thrift,解压并通过如下命令编译安装:
./configure --prefix=/usr/local/ \
--with-boost=/usr/local \
--with-libevent=/usr/local \
--without-ruby ## 不需要的语言可以通过 --without-[language] 去掉
运行时可能会报错:Bison version 2.5 or higher must be installed on the system!
。参考 How to install bison on mac OSX 解决:
brew install bison
brew link bison --force
brew link bison
是在系统路径下添加 bison 的 symlinks。在装完 thrift 之后记得:
brew unlink bison
Ubuntu 下 Thrift 配置
参考链接
[1] Debian/Ubuntu install
[2] Building from source
[3] Apache Thrift Tutorial
安装依赖
执行命令:
sudo apt-get install automake bison flex g++ git libboost1.55-all-dev libevent-dev libssl-dev libtool make pkg-config
安装 Thrift
在 Thrift 官网 下载最新的打包文件,解压后进入文件夹,输入如下命令编译安装:
./configure && make && sudo make install
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 脚本文件如下:
namespace cpp MathServer
service MathService{
i32 add (1:i32 a, 2:i32 b),
i32 sub (1: