RPC服務(wù)框架Apache Thrift學(xué)習(xí)筆記--簡單示例

前置聲明:
如果讀者還沒安上一篇文章的流程安裝好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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容