Thrift 小白最简单入门例子

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值