一、boost安裝
要用thrift必須先安裝boost,thrift依賴boost庫
參考:https://blog.csdn.net/faihung/article/details/88128928
1、boost下載
安裝boost_1_59_0
2、執行腳本
./bootstrap.sh
3、執行./sh
sudo ./b2
4、安裝
sudo ./b2 install
二、thrift安裝
版本說明:
ubuntu 16.04
thrift-0.9.3.tar.gz
1、下載thrift安裝包
(1)下載安裝包
(2)解壓thrift安裝包
2、執行配置命令
先進入解壓後的thrift安裝包
執行配置命令
3、執行編譯指令make
4、執行安裝命令make install
5、 配置/etc/ld.so.conf文件
將/usr/local/lib添加到ld.so.conf文件中
vim /etc/ld.so.conf
寫上如下一句:/usr/local/lib
保存退出,source /etc/ld.so.conf
此時好像還沒有生效,執行一下如下語句:
ldconfig
6、查看安裝結果
此部分參考:
三、應用thrift
本部分參考以下鏈接內容:
https://www.cnblogs.com/lizhenghn/p/5247266.html
應用說明:創建一個server端和client端程序,client通過hello接口發送自己的名字,server端回覆。
1、建立hello.thrift文件
文件內容如下:
service HelloService
{
void hello(1: string name);
}
2、對hello.thrift文件編譯
編譯指令:
thrift --gen cpp hello.thrift
編譯後生成gen-cpp目錄
對HelloService_server.skeleton.cpp備份,並拷貝重命名爲server.cpp
3、修改server.cpp的內容
class HelloServiceHandler : virtual public HelloServiceIf {
public:
HelloServiceHandler() {
// Your initialization goes here
}
void hello(const std::string& name) {
// Your implementation goes here
// 這裏只簡單打印出client傳入的名稱
printf("hello, I got your name %s\n", name.c_str());
}
};
編譯server.cpp
g++ -o server hello_constants.cpp HelloService.cpp hello_types.cpp server.cpp -I/usr/local/include/thrift -L/usr/local/lib -lthrift
編譯結果如下所示:
4、編寫客戶端程序
編寫client.cpp(此文件由自己新建)
編輯內容如下
#include <stdio.h>
#include <string>
#include "transport/TSocket.h"
#include "protocol/TBinaryProtocol.h"
#include "server/TSimpleServer.h"
#include "transport/TServerSocket.h"
#include "transport/TBufferTransports.h"
#include "hello_types.h"
#include "HelloService.h"
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using boost::shared_ptr;
int main()
{
shared_ptr<TTransport> socket(new TSocket("localhost", 9090));
shared_ptr<TTransport> transport(new TBufferedTransport(socket));
shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
HelloServiceClient client(protocol);
try
{
transport->open();
client.hello("cpper.info");
transport->close();
}
catch(TException& tx)
{
printf("ERROR:%s\n",tx.what());
}
}
5、運行測試
在一個窗口開啓server
在另一個窗口開啓client
測試結果如下所示:
測試成功!
6、對以上應用做進一步分析
文件關係如下: