python thrift 服務端與客戶端使用

1、簡介

thrift是一個軟件框架,用來進行可擴展且跨語言的服務的開發。它結合了功能強大的軟件堆棧和代碼生成引擎,以構建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 這些編程語言間無縫結合的、高效的服務。python

2、安裝

1.下載地址

 http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.2/thrift-0.9.2.tar.gz

2.安裝

 [root@localhost ~]# yum -y groupinstall "Development Tools"
[root@localhost ~]# yum -y install libevent-devel zlib-devel openssl-devel autoconf automake
[root@localhost ~]#  wget http://ftp.gnu.org/gnu/bison/bison-2.5.1.tar.gz 
[root@localhost ~]# tar xf bison-2.5.1.tar.gz
[root@localhost ~]# cd bison-2.5.1
[root@localhost ~]# ./configure --prefix=/usr
[root@localhost ~]# make
[root@localhost ~]# make install
[root@localhost ~]# tar xf thrift-0.9.2.tar.gz 
[root@localhost ~]# cd thrift-0.9.2
[root@localhost thrift-0.9.2]# ./configure -with-lua=no

3.安裝python插件

pip install thrift

3、準備服務器端

1.編輯接口文件helloworld.thrift:

#!/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!"

4、準備客戶端

#!/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:
  #創建socket
  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.這個就是thrift的服務端和客戶端的實現小案例。通常只有在多種語言聯合開發時纔會用到,若是是一種語言的話,thrift就沒有用武之地了。在多語言開發時,咱們拿到其餘語言的thrift文件,就能夠直接使用咱們的python做爲客戶端去調用thrift中的函數就能夠了,或者咱們提供thrift服務端文件供別的語言調用,總起來講仍是很方便的,但願上面的例子可讓你們明白thrift的簡單應用!apache

相關文章
相關標籤/搜索