2019独角兽企业重金招聘Python工程师标准>>>
编译版本: python 2.7+, thrift-0.10.0.exe
参考文档:
http://www.tuicool.com/articles/FnY3eiQ
http://www.cnblogs.com/enternal/p/5275455.html
https://my.oschina.net/u/780876/blog/691293
https://my.oschina.net/michao/blog/550416
项目目录结构:
<项目名>:
test: 测试代码包
ds: 数据结构包,thrift生成的py放在这里
thrift: thrift文件存储目录
代码:
helloworld.thrift
#helloworld.thrift
#建议设定namespace
namespace java org.sl.thrift
namespace py slthrift
service Hello {
string helloString(1:string word)
}
生成python代码 (windows下,需要下载thrift编译器, http://apache.fayea.com/thrift/0.10.0/thrift-0.10.0.exe,建议改个名)
thrift --gen py -out ../ds helloworld.thrift
执行后,会在ds目录下生成 (子目录slthrift)python代码
test目录下,python 测试代码
thriftserver.py
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'shanl'
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('../ds/slthrift') #注意这里
from slthrift import Hello
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
SERVICE_CFG = {
'ip': '0.0.0.0', #向所有ip开放
'port': 9000
}
class HelloHandler(Hello.Iface):
def helloString(self, word):
ret = "Received: " + word
return ret
handler = HelloHandler()
processor = Hello.Processor(handler)
transport = TSocket.TServerSocket(SERVICE_CFG['ip'], SERVICE_CFG['port'])
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print "thrift server listen in '%s:%s'." % (SERVICE_CFG['ip'], SERVICE_CFG['port'])
server.serve()
print "done!"
thriftclient.py
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'shanl'
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append('../ds/slthrift')
from slthrift import Hello
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
import random
SERVICE_CFG = {
'ip': '127.0.0.1',
'port': 9000
}
transport = TSocket.TSocket(SERVICE_CFG['ip'], SERVICE_CFG['port'])
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = Hello.Client(protocol)
transport.open()
for i in xrange(100):
print client.helloString('%s' % (random.randint(1000, 9999)))
transport.close()