您的位置:首页 > 其它

RPC-Thrift简单应用

2016-08-24 21:07 141 查看
Thrift是Facebook开源的一款RPC框架,使用起来非常方便。下面举一个简单的小例子。

安装包下载

wget http://www.apache.org/dist//thrift/0.9.3/thrift-0.9.3.tar.gz -O thrift-0.9.3.tar.gz


安装这个需要可能需要先升级bison

wget http://ftp.gnu.org/gnu/bison/bison-2.5.1.tar.gz tar xvf bison-2.5.1.tar.gz
cd bison-2.5.1
./configure --prefix=/usr
make
sudo make install
cd ..


例子

一个调用远程服务的计算器应用

calculator.thrift

service Calculator {
string calc(1:string expr)
}


执行thrift –gen py calclulator.thrift

自动生成gen-py目录,里面含有对Calculator的一些定义代码

server.py

#!/usr/bin/env python

import socket
import sys
sys.path.append('./gen-py')

from calculator import Calculator
from calculator.ttypes import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

class CalculatorHandler:
def calc(self, msg):
res = eval(msg)
return str(res)

handler = CalculatorHandler()
processor = Calculator.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!"


client.py

#!/usr/bin/env python

import sys
sys.path.append('./gen-py')

from calculator import Calculator

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

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

while True:
data = raw_input("input data: ")
if len(data) == 0: break
print "length of data: ", len(data)

op_res = client.calc(data)
print "received from server side:  " + op_res
print "--------------------------------"

transport.close()

except Thrift.TException, ex:
print "%s" % (ex.message)


开启server端服务

./server.py
Starting thrift server in python...


然后开启client端

./client.py
input data: 1+3
length of data:  3
received from server side:  4
--------------------------------
input data: 2*5
length of data:  3
received from server side:  10
--------------------------------
input data: 2**3
length of data:  4
received from server side:  8
--------------------------------
input data:


参考链接:

1. http://sunliwen.com/2012/02/apache-thrift-on-ubuntu-10-04/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thrift