[zz]使用thrift做c++,java和python的相互調用[zz]使用thrift做c++,java和python的相互調用

來源:互聯網
上載者:User

[zz]使用thrift做c++,java和python的相互調用 - zaleilynn - 部落格園

[zz]使用thrift做c++,java和python的相互調用

linux上安裝thrift見
http://jinghong.iteye.com/blog/1102535
thrift做為跨語言調用的方案有高效,支援語言較多,成熟等優點;代碼侵入較強是其弱點。
下面記錄以C++做伺服器,C++,java和python做用戶端的樣本,這個和本人現在工作環境吻合,使用多線程長串連的socket來建立高效分布式系統的跨語言調用平台。
遺憾的是目前版本(0.7.0)的C語言還不支援Compact協議,導致在現在的環境中nginx c module調用thrift要使用binary協議。thriftTeam Dev似乎對C語言不太感冒。
1.定義idl檔案acsuser.thrift
Idl代碼  收藏代碼

    struct User{ 
     1: string uid, 
     2: string uname, 
     3: bool usex, 
     4: i16 uage, 
    } 
    service UserService{ 
     void add(1: User u), 
     User get(1: string uid), 
    } 

2.產生c++,java和python代碼架構
Shell代碼  收藏代碼

    thrift -r --gen cpp acsuser.thrift  
    thrift -r --gen java acsuser.thrift  
    thrift -r --gen py acsuser.thrift  

這時產生子目錄gen-cpp,gen-java,gen-py

3.產生C++服務端代碼
Shell代碼  收藏代碼

    cp gen-cpp/UserService_server.skeleton.cpp UserServer.cpp 

修改UserServer.cpp
C++代碼  收藏代碼

    #include "UserService.h" 
    #include <config.h> 
    //#include <protocol/TBinaryProtocol.h> 
    #include <protocol/TCompactProtocol.h> 
    #include <server/TSimpleServer.h> 
    #include <transport/TServerSocket.h> 
    #include <transport/TBufferTransports.h> 
    #include <concurrency/ThreadManager.h> 
    #include <concurrency/PosixThreadFactory.h> 
    #include <server/TThreadPoolServer.h> 
    #include <server/TThreadedServer.h> 
     
    using namespace ::apache::thrift; 
    using namespace ::apache::thrift::protocol; 
    using namespace ::apache::thrift::transport; 
    using namespace ::apache::thrift::server; 
    using namespace ::apache::thrift::concurrency; 
     
    using boost::shared_ptr; 
     
    class UserServiceHandler : virtual public UserServiceIf { 
     public: 
      UserServiceHandler() { 
        // Your initialization goes here 
      } 
     
      void add(const User& u) { 
        // Your implementation goes here 
        printf("uid=%s uname=%s usex=%d uage=%d\n", u.uid.c_str(), u.uname.c_str(), u.usex, u.uage); 
      } 
     
      void get(User& _return, const std::string& uid) { 
        // Your implementation goes here 
        _return.uid = "leo1"; 
        _return.uname = "yueyue"; 
        _return.usex = 1; 
        _return.uage = 3; 
        printf("uid=%s uname=%s usex=%d uage=%d\n", _return.uid.c_str(), _return.uname.c_str(), _return.usex, _return.uage); 
      } 
     
    }; 
     
    int main(int argc, char **argv) { 
      shared_ptr<UserServiceHandler> handler(new UserServiceHandler()); 
      shared_ptr<TProcessor> processor(new UserServiceProcessor(handler)); 
      shared_ptr<TProtocolFactory> protocolFactory(new TCompactProtocolFactory()); 
      shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory()); 
      shared_ptr<TServerTransport> serverTransport(new TServerSocket(9090)); 
     
      shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(10); 
      shared_ptr<PosixThreadFactory> threadFactory = shared_ptr<PosixThreadFactory>(new PosixThreadFactory()); 
      threadManager->threadFactory(threadFactory); 
      threadManager->start(); 
      printf("start user server...\n"); 
     
      TThreadPoolServer server(processor, serverTransport, transportFactory, protocolFactory, threadManager); 
      server.serve(); 
      return 0; 
    } 

注意這段代碼使用TCompactProtocol,需要#include <config.h>
另外這個是Blocking的多線程伺服器

4.產生C++的client檔案UserClient.cpp
C++代碼  收藏代碼

    #include "UserService.h" 
    #include <config.h> 
    #include <transport/TSocket.h> 
    #include <transport/TBufferTransports.h> 
    #include <protocol/TCompactProtocol.h> 
     
    using namespace apache::thrift; 
    using namespace apache::thrift::protocol; 
    using namespace apache::thrift::transport; 
     
    using boost::shared_ptr; 
     
    int main(int argc, char **argv) { 
            boost::shared_ptr<TSocket> socket(new TSocket("localhost", 9090)); 
            boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket)); 
            boost::shared_ptr<TProtocol> protocol(new TCompactProtocol(transport)); 
     
            transport->open(); 
     
            User u; 
            u.uid = "leo"; 
            u.uname = "yueyue"; 
            u.usex = 1; 
            u.uage = 3; 
     
            UserServiceClient client(protocol); 
            client.add(u); 
     
            User u1; 
            client.get(u1,"lll"); 
     
            transport->close(); 
            printf("uid=%s uname=%s usex=%d uage=%d\n", u1.uid.c_str(), u1.uname.c_str(), u1.usex, u1.uage); 
            return 0; 
    } 

5.產生Makefile
Makefile代碼  收藏代碼

    BOOST_DIR = /usr/local/include/boost/ 
    THRIFT_DIR = /usr/local/include/thrift 
    LIB_DIR = /usr/local/lib 
    GEN_SRC = ./gen-cpp/acsuser_types.cpp ./gen-cpp/acsuser_constants.cpp ./gen-cpp/UserService.cpp 
    default: server client 
    server: UserServer.cpp 
            g++ -g -o UserServer -I${THRIFT_DIR} -I${BOOST_DIR}  -I./gen-cpp -L${LIB_DIR} -lthrift UserServer.cpp ${GEN_SRC} 
    client: UserClient.cpp 
            g++ -g -o UserClient -lm -pthread -lz -lrt -lssl -I${THRIFT_DIR} -I${BOOST_DIR}  -I./gen-cpp -L${LIB_DIR} -lthrift UserClient.cpp ${GEN_SRC} 
    clean: 
            $(RM) -r UserServer UserClient 

6.啟動c++ server
Shell代碼  收藏代碼

    ./UserServer 

7.測試c++ client
Shell代碼  收藏代碼

    ./UserClient 

8.寫java client檔案UserClient.java
Java代碼  收藏代碼

    import org.apache.thrift.TException; 
    import org.apache.thrift.protocol.TCompactProtocol; 
    import org.apache.thrift.protocol.TProtocol; 
    import org.apache.thrift.transport.TFramedTransport; 
    import org.apache.thrift.transport.TNonblockingSocket; 
    import org.apache.thrift.transport.TSocket; 
    import org.apache.thrift.transport.TTransport; 
    import org.apache.thrift.transport.TTransportException; 
     
    //import UserService.Client; 
     
    public class UserClient { 
        private void start() { 
            try { 
                TTransport socket = new TSocket("localhost", 9090); 
                //TTransport transport = new TFramedTransport(socket); 
                TProtocol protocol = new TCompactProtocol(socket); 
     
                UserService.Client client = new UserService.Client(protocol); 
                socket.open(); 
                System.out.println(client.get("lll")); 
     
                User u = new User(); 
                u.uid="leojava"; 
                u.uname="yueyue"; 
                u.usex=true; 
                u.uage=3; 
                client.add(u); 
                socket.close(); 
     
            } catch (TTransportException e) { 
                e.printStackTrace(); 
            } catch (TException e) { 
                e.printStackTrace(); 
            } 
        } 
     
        public static void main(String[] args) { 
            UserClient c = new UserClient(); 
            c.start(); 
     
        } 
    } 

編譯和運行java client
Shell代碼  收藏代碼

    javac -classpath /usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar:/usr/local/lib/slf4j-api-1.5.8.jar UserClient.java ./gen-java/*.java 
    java -classpath .:./gen-java:/usr/local/lib/libthrift-0.7.0.jar:/usr/local/lib/log4j-1.2.14.jar:/usr/local/lib/commons-logging-1.1.1.jar:/usr/local/lib/slf4j-api-1.5.8.jar:/usr/local/lib/slf4j-log4j12-1.5.8.jar UserClient 

9.寫Python client檔案PythonClient.py
Python代碼  收藏代碼

    #!/usr/bin/env python 
    import sys 
    sys.path.append('./gen-py') 
    from acsuser import UserService 
    from acsuser.ttypes import * 
    from thrift import Thrift 
    from thrift.transport import TSocket 
    from thrift.transport import TTransport 
    from thrift.protocol import TCompactProtocol 
     
    # Make socket 
    transport = TSocket.TSocket('localhost', 9090) 
    # Buffering is critical. Raw sockets are very slow 
    transport = TTransport.TBufferedTransport(transport) 
    # Wrap in a protocol 
    protocol = TCompactProtocol.TCompactProtocol(transport) 
    # Create a client to use the protocol encoder 
    client = UserService.Client(protocol) 
    # Connect! 
    transport.open() 
    # Call Server services   
    u = client.get('lll') 
    print 'uid=%s uname=%s usex=%d u.uage=%d' %(u.uid,u.uname,u.usex,u.uage) 
     
    u1 = User() 
    u1.uid='leo' 
    u1.uname='yueyue' 
    u1.usex=1 
    u1.uage=3 
    client.add(u1) 

執行python client代碼
Shell代碼  收藏代碼

    chmod 777 PythonClient.py 
    ./PythonClient.py 

    sample.tar.gz (2.1 KB)
    描述: 源檔案
    下載次數: 22

分類: thrift

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.