thrift開發的例子(一)---python為例
阿新 • • 發佈:2019-02-19
1.編寫thrift介面檔案
2.thrift --gen 開發語言 thrift介面描述檔案
如:thrift --gen cpp student.thrift
thrift --gen py student.thrift
3.利用生成的檔案程式碼進行開發 1.簡單的例子 struct employee{ 1:i16 id, 2:string name } service HelloWorld{ string ping(), string sayHello(1:string msg,2:employee e) } 2.thrift-0.9.2.exe --gen py a.thrift (linux 下thrift --gen py a.thrift)
3.開發例子
客戶端c.py
#coding=utf-8
import sys
sys.path.append('./gen-py')
from a.HelloWorld import Client
from a.ttypes import employee
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
transport = TSocket.TSocket('localhost', 9090)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Client(protocol)
transport.open()
print client.ping()
e = employee(1,'李小四')
print client.sayHello("!",e)
transport.close()
伺服器端開發s.py
#!/usr/bin/env python
import socket
import sys
sys.path.append('./gen-py')
from a.HelloWorld import Processor
from a.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class HelloHandler:
def ping(self):
return "ping"
def sayHello(self, msg, e):
print msg
print e.id
print e.name
return 'hello '+e.name
handler = HelloHandler()
processor = Processor(handler)
transport = TSocket.TServerSocket("localhost", 9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "Starting thrift server in python..."
server.serve()
print "done!"
附錄:thrift資料型別規則
【基礎型別】
(1)bool:布林型別(true或false)
(2)byte:8位有符號整數
(3)i16:16位有符號整數
(4)i32:32位有符號整數
(5)i64:64位有符號整數
(6)double:64位浮點數
(7)string:文字字串,使用UTF-8編碼
【容器】
(1)list容器:一個元素可重複的有序列表。會被轉換成C++中的vector,Java中的ArrayList,指令碼語言中的陣列等。
(2)set容器:一個元素不可重複的無序集合。會轉換成C++中的set,Java中的HashSet、Python中的Set等。(熟悉PHP的同學可能會問“PHP並不支援set型別,怎麼辦”,在PHP語言中,
thrift會將set容器轉換成List。)
(3)map容器:一個含有多個key:value鍵值對的結構。會被轉換成C++中的map,Java中的HashMap,PHP中的關聯陣列,Python/Ruby中的dictionary等。
【結構體】
struct User{
1:i32 id,
2:string name
}
thrift --gen py student.thrift
3.利用生成的檔案程式碼進行開發 1.簡單的例子 struct employee{ 1:i16 id, 2:string name } service HelloWorld{ string ping(), string sayHello(1:string msg,2:employee e) } 2.thrift-0.9.2.exe --gen py a.thrift (linux 下thrift --gen py a.thrift)