手把手教你Win平臺Thrift編譯之 C++代碼實戰

1. Thrift簡介

Thrift是由FB公司開源的一款RPC通訊庫,它結合了功能強大的軟件堆棧和代碼生成引擎,允許定義一個簡單的定義文件中的數據類型和服務接口,以作為輸入文件,編譯器生成代碼用來方便地生成RPC客戶端和服務器通信的無縫跨編程語言。具體的介紹我想大家可以直接google或者baidu到更詳細的內容,再此不再詳述。

手把手教你Win平臺Thrift編譯之 C++代碼實戰

2. Thrift源碼下載

最新版本的thrift, 直接在git上下載最新代碼。

git clone https://github.com/apache/thrift.git

本次工程使用的是release最新發布版本(0.11.0)。

使用git命令切換到tag版本0.11.0。

git checkout -b [本地分支] [遠端分支]

3. thrift編譯

編譯依賴庫:

boost、openssl、libevent

開發平臺:

Win10、VS2013

編譯thrift過程中要把boost、openssl、libevent幾個庫包含進去。

windows下下面語句編譯錯誤,max()和STL中的衝突。

maxBufferSize_ = std::numeric_limits::max();

修改為

maxBufferSize_ = (std::numeric_limits::max)(); 

4. thrift文件

3.1 thrift文件編寫(msg.thrift)

namespace cpp msgIFstruct MSG_INFO{1: string strMsg,}service MsgServ{MSG_INFO Msg_GetMsgInfo(1: MSG_INFO tMsgInfo),}

3.2 文件生成命令:

thrift --gen cpp msg.thrift

5. ThriftServer

5.1 工程屬性

主要有以下三個方面配置:

  • C++附加包含目錄

手把手教你Win平臺Thrift編譯之 C++代碼實戰

  • 鏈接中的附加庫目錄

手把手教你Win平臺Thrift編譯之 C++代碼實戰

  • 鏈接時所依賴lib庫

手把手教你Win平臺Thrift編譯之 C++代碼實戰

5.2 ThriftServer代碼實現

#define SERV_CONN_PORT 8090bool StartServ(){ ::apache::thrift::stdcxx::shared_ptr handler(new MsgServHandler()); ::apache::thrift::stdcxx::shared_ptr processor(new MsgServProcessor(handler)); ::apache::thrift::stdcxx::shared_ptr serverTransport(new TServerSocket(SERV_CONN_PORT)); ::apache::thrift::stdcxx::shared_ptr transportFactory(new TBufferedTransportFactory()); ::apache::thrift::stdcxx::shared_ptr protocolFactory(new TBinaryProtocolFactory()); ::apache::thrift::stdcxx::shared_ptr threadManager = ThreadManager::newSimpleThreadManager(10); ::apache::thrift::stdcxx::shared_ptr threadFactory = ::apache::thrift::stdcxx::shared_ptr(new PlatformThreadFactory()); threadManager->threadFactory(threadFactory); threadManager->start(); TThreadedServer server(processor, serverTransport, transportFactory, protocolFactory, threadFactory);  server.serve(); return true;}void MsgServHandler::Msg_GetMsgInfo(MSG_INFO& _return, const MSG_INFO& tMsgInfo){ if (!tMsgInfo.strMsg.empty()) { std::cout << "Recv From Client:" << tMsgInfo.strMsg << std::endl; _return.__set_strMsg("Server Reply Msg"); } return;}

6. ThriftClient

工程屬性配置和上面相同。

客戶端代碼如下:

#define SERV_CONN_PORT 8090int main(){ ::apache::thrift::stdcxx::shared_ptr socket(new TSocket("localhost", SERV_CONN_PORT)); ::apache::thrift::stdcxx::shared_ptr transport(new TBufferedTransport(socket)); ::apache::thrift::stdcxx::shared_ptr protocol(new TBinaryProtocol(transport));  MsgServClient thriftClient(protocol);  try { transport->open(); MSG_INFO tMsgClientInfo; tMsgClientInfo.strMsg = "HelloWorld!"; thriftClient.send_Msg_GetMsgInfo(tMsgClientInfo); MSG_INFO tMsgRecvInfo; thriftClient.recv_Msg_GetMsgInfo(tMsgRecvInfo); std::cout << "ServerInfo:" << tMsgRecvInfo.strMsg; transport->close(); } catch (TException& tx) { std::cout << "ERROR: " << tx.what() << std::endl; } getchar(); return 0;}

7.運行效果

手把手教你Win平臺Thrift編譯之 C++代碼實戰


分享到:


相關文章: