ENG: https://thrift.apache.org/tutorial/cpp
中文:https://my.oschina.net/zmlblog/blog/177245
https://blog.csdn.net/feng973/article/details/70160571
https://www.cnblogs.com/zhaoxd07/p/5387215.html
Step 0: create multiple.thrift
namespace java tutorial
namespace py tutorial
typedef i32 int // We can use typedef to get pretty names for the types we are using
service MultiplicationService
{
int multiply(1:int n1, 2:int n2),
}
Step 1: gen multiple.thrift
thrift --gen py multiple.thrift
产生gen-py 目录,下面有一个turtorial文件夹,有以下目录
Step3, create Server, multiple_server.py :
#!/usr/bin/env python
import sys
sys.path.append('gen-py')
from tutorial import MultiplicationService
from tutorial.ttypes import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
# implement your function in Handler
class MultiplicationHandler:
def multiply(self, n1, n2):
return n1 * n2
handler = MultiplicationHandler()
processor = MultiplicationService.Processor(handler)
transport = TSocket.TServerSocket("0.0.0.0", port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print('Starting python server...')
server.serve()
print('done!')
Step4: create Client, multiple_client.py
#!/usr/bin/env python
import sys
sys.path.append('gen-py')
from tutorial import MultiplicationService
from tutorial.ttypes import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
# Make socket
transport = TSocket.TSocket('localhost', 9090)
# Buffering is critical. Raw sockets are very slow
transport = TTransport.TBufferedTransport(transport)
# Wrap in a protocol
protocol = TBinaryProtocol.TBinaryProtocol(transport)
# Create a client to use the protocol encoder
client = MultiplicationService.Client(protocol)
# Connect!
transport.open()
product = client.multiply(4,5)
print '4*5=%d' % (product)
# Close!
transport.close()
except Thrift.TException, tx:
print '%s' % (tx.message)
Step 5: run server & client
python multiple_server.py &
python multiple_client.py
###### Result ######
4*5=20