【Thrift一】Thrift安裝部署

Thrift安裝部署

下載源碼包

wget http://apache.fayea.com/thrift/0.9.3/thrift-0.9.3.tar.gzphp

安裝g++

centos:yum install gcc gcc-c++java

若是沒有安裝g++,沒法編譯python

解壓Thrift安裝包

tar -xvf thrift-0.9.3.tar.gzc++

安裝boost開發工具

  1. 進入thrift-0.9.3目錄apache

  2. 運行命令:yum install boost-devel.x86_64centos

  3. 運行命令:yum install boost-devel-staticruby

  4. 運行命令:./configure --with-cpp --with-boost --with-python --without-csharp --with-java --without-erlang --without-perl --with-php --without-php_extension --without-ruby --without-haskell --without-go服務器

  5. 編譯,命令:makeapp

  6. 編譯完成以後安裝,命令:make installsocket

  7. 出現thrift命令提示表示Thrift安裝成功

測試(python版)

  1. 建立RecSys.thrift文件
service RecSys {
    string rec_data(1:string data)
}
  1. 建立server.py文件
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
sys.path.append('gen-py')

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

from RecSys import RecSys
from RecSys.ttypes import *

class RecSysHandler(RecSys.Iface):
    def rec_data(self, a):
        print "Receive: %s" %(a)
        return "ok"

if __name__ == "__main__":

    # 實例化handler
    handler = RecSysHandler()

    # 設置processor
    processor = RecSys.Processor(handler)

    # 設置端口
    transport = TSocket.TServerSocket('localhost', port=9900)

    # 設置傳輸層
    tfactory = TTransport.TBufferedTransportFactory()

    # 設置傳輸協議
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)

    print 'Starting the server...'
    server.serve()
    print 'done'
  1. 建立client.py文件
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
sys.path.append("gen-py") // 將第4步驟產生的目錄加載進來

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

from RecSys import RecSys
# from demo.ttypes import *

try:
    # Make Socket
    # 創建socket, IP 和port要寫對
    transport = TSocket.TSocket('localhost', 9900)

    # Buffering is critical. Raw sockets are very slow
    # 選擇傳輸層,這塊要和服務器的設置同樣
    transport = TTransport.TBufferedTransport(transport)

    # Wrap in a protocol
    # 選擇傳輸協議,這個也要和服務器保持一致,負責沒法通訊
    protocol = TBinaryProtocol.TBinaryProtocol(transport)

    client = RecSys.Client(protocol)

    # Connect!
    transport.open()

    # Call server services
    rst = client.rec_data("are you ok!")
    print rst

    # close transport
    transport.close()
except Thrift.TException, ex:
    print "%s" % (ex.message)
  1. 運行命令:thrift --gen py RecSys.thrift
    • 運行完以後會在當前目錄生成一個gen-py的文件夾,裏面有模塊的名字之類的東西

    • 運行命令:python server.py,啓動服務端

    • 運行命令:python client.py,啓動客戶端,並能收到服務端發出的信息

相關文章
相關標籤/搜索