前置聲明:
如果讀者還沒安上一篇文章的流程安裝好Thrift,那建議您先看上一篇文章
開始示例:
第一步:首選創(chuàng)建一個(gè)后綴為.thrift文件,取名為tutorial.thrift
文件內(nèi)容如下圖1,大致功能是有個(gè)叫Tutorial的服務(wù),它有一個(gè)ping的接口,返回一個(gè)32為的有符號整數(shù):
圖1
第二步:用Thrift自動(dòng)生成相應(yīng)語言的代碼,比如C++, Python, PHP等對應(yīng)的server端以及client端代碼,而且能在它們之間無縫的結(jié)合
C++
thrift --gen cpp tutorial.thrift
這個(gè)命令之后就會(huì)在當(dāng)前目錄下多出 gen-cpp目錄Python
thrift --gen py tutorial.thrift
這個(gè)命令之后就會(huì)在當(dāng)前目錄下多出 gen-py目錄
PHP
thrift --gen php tutorial.thrift
這個(gè)命令之后就會(huì)在當(dāng)前目錄下多出 gen-php目錄
第三步:運(yùn)行相應(yīng)的server服務(wù)以及和client端進(jìn)行通信(server和client是可以混搭的,下面會(huì)介紹用python的client和C++的server進(jìn)行通信)
C++ Server
改下紅框里的代碼
g++ -DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H -Wall -I/usr/local/include/thrift *.cpp -L/usr/local/lib -lthrift -o simple_server
然后運(yùn)行可執(zhí)行文件就能起服務(wù)了
./simple_server
C++ Client
Thrift不會(huì)像Server那樣自動(dòng)生成Client的文件,需要自己改
g++ -Wall -I/usr/local/include/thrift -c client.cpp -o client.o
g++ -Wall -I/usr/local/include/thrift -c Tutorial.cpp -o Tutorial.o
g++ -Wall -I/usr/local/include/thrift -c tutorial_constants.cpp -o tutorial_constants.o
g++ -Wall -I/usr/local/include/thrift -c tutorial_types.cpp -o tutorial_types.o
g++ -L/usr/local/lib client.o Tutorial.o tutorial_constants.o tutorial_types.o -o client -lthrift
然后運(yùn)行可執(zhí)行文件就能調(diào)用服務(wù)器接口了
./client
會(huì)返回Hello World
Python Server
執(zhí)行運(yùn)行:
python server.py
Python Client
用python的client和C++的server進(jìn)行通信:
其他:
運(yùn)行C++的時(shí)候可能會(huì)報(bào)、error:./CppServer: error while loading shared libraries: libthrift-1.0.0-dev.so: cannot open shared object file: No such file or directory
解決方法:
1、使用find命令查找缺失的libthrift-1.0.0-dev.so共享庫文件所在位置:find /usr/local/ -name "libthrift-1.0.0*”
2、將找到的目錄位置寫入 /etc/ld.so.conf 配置文件,這個(gè)文件記錄了編譯時(shí)使用的動(dòng)態(tài)鏈接庫的路徑,使用命令:sudo vim /etc/ld.so.conf ,在末尾增加報(bào)錯(cuò)文件的路徑
3、然后使用ldconfig命令,使配置生效
4.再運(yùn)行測試程序正常
參考文章:
http://thrift.apache.org/tutorial/
http://blog.csdn.net/ceasadan/article/details/52277136