1. 程式人生 > >python實現一個簡單的thirft客戶端和服務端

python實現一個簡單的thirft客戶端和服務端

建立thrift檔案

service Hello {
    string get()
}

使用thrift 建立服務需要的元件

thrift --gen py hello.thrift

得到以惡搞gen-py檔案,請將該檔案放到新建的python專案下面

編寫服務端

# coding=utf-8
from thrift_server.gen.hello.Hello import Processor
from thrift_server.gen.hello.ttypes import *
from thrift.Thrift import TType, TMessageType, TException
from
thrift.Thrift import TProcessor from thrift.transport import TSocket from thrift.protocol import TBinaryProtocol, TProtocol from thrift.server import TServer import logging class HelloHandler: def get(self): return "hello world" def run(): handler = HelloHandler() processor = Processor(handler) # 監聽埠
transport = TSocket.TServerSocket('localhost', 9234) # 選擇傳輸層 tfactory = TTransport.TBufferedTransportFactory() # 選擇傳輸協議 pfactory = TBinaryProtocol.TBinaryProtocolFactory() # 建立服務端 server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) server.setNumThreads(5
) logging.info('start thrift serve in python') server.serve() if __name__ == '__main__': run()

編寫客戶端

from thrift_server.gen.hello.Hello import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:
    transport = TSocket.TSocket('localhost', 9234)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Client(protocol)
    transport.open()

    print 'start'
    ret = client.get()
    print ret
    transport.close()
except Thrift.TException as e:
    print 'exception'
    print e

服務呼叫

首先啟動服務端,再執行客戶端,執行結果如下 這裡寫圖片描述

注意事項

python需要安裝thrift,如缺少其它元件,也可以類似安裝

pip install thrift