一、简介
thrift是一个软件框架,用来进行可扩展且跨语言的服务的开发。它结合了功能强大的软件堆栈和代码生成引擎,以构建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 这些编程语言间无缝结合的、高效的服务。
二、安装
1.下载地址
1
|
http: //www .apache.org /dyn/closer .cgi?path= /thrift/0 .9.2 /thrift-0 .9.2. tar .gz
|
2.安装
1
2
3
4
5
6
7
8
9
10
11
|
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost ~]
[root@localhost thrift-0.9.2]
|
3.安装python插件
三、准备服务器端
1.编辑接口文件 helloworld.thrift:
1
2
3
4
|
service HelloWorld {
string ping (),
string say(1:string msg)
}
|
2.编辑 server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#!/usr/bin/env python
import socket
import sys
sys.path.append( './gen-py' )
from helloworld import HelloWorld
from helloworld.ttypes import *
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class HelloWorldHandler:
def ping (self):
return "pong"
def say(self, msg):
ret = "Received: " + msg
print ret
return ret
handler = HelloWorldHandler()
processor = HelloWorld.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!"
|
四、准备客户端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
#!/usr/bin/env python
import sys
sys.path.append( './gen-py' )
from helloworld import HelloWorld
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 = HelloWorld.Client(protocol)
transport. open ()
print "client - ping"
print "server - " + client. ping ()
print "client - say"
msg = client.say( "Hello!" )
print "server - " + msg
transport.close()
except Thrift.TException, ex:
print "%s" % (ex.message)
|
ps:亲测通过,吐槽一下,这东西以前都没有听说过,就要拿来开发,还要只是用客户端
本文转自wangfeng7399 51CTO博客,原文链接:http://blog.51cto.com/wangfeng7399/1696108,如需转载请自行联系原作者