打赏
禅在心中
东风夜放花千树,更吹落、星如雨。宝马雕车香满路。凤箫声动,玉壶光转,一夜鱼龙舞。 蛾儿雪柳黄金缕,笑语盈盈暗香去。众里寻他千百度,蓦然回首,那人却在,灯火阑珊处。

1、下载thrift,下载地址:http://archive.apache.org/dist/thrift/0.9.3/

2、在编写python的thrift代码时,需要先安装thrift module,下载路径:https://pypi.python.org/pypi/thrift/0.9.1

3、安装thrift:在C盘新建一个Thtift文件夹,将下载的thrift-0.9.3.exe重新命名为thrift.exe后放到Thtift文件夹下,将该路径添加到环境变量,检验是否安装成功:在命令行中输入:

即可以看到安装后的版本信息。

4、thrift 采用IDL(Interface Definition Language)来定义通用的服务接口,并通过生成不同的语言代理实现来达到跨语言、平台的功能。在thrift的IDL中可以定义以下一些类型:基本数据类型,结构体,容器,异常、服务。

thrift脚本:

const string HELLO_YK = "yk"
service HelloWorld {
void ping(),
string sayHello(),
string sayMsg(1:string msg)
}

thrift脚本通过Thrift编辑器生成所要求的python开发语言代码。即:

  

 

  5、Thrift是一个典型的CS结构,客户端和服务端可以使用不同的语言开发。本文以python为例:

PythonServer.py:

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
 
import socket

class HelloWorldHandler:
  def __init__(self):
    self.log = {}

  def ping(self):
    print "ping()"

  def sayHello(self):
    print "sayHello()"
    return "say hello from " + socket.gethostbyname(socket.gethostname())

  def sayMsg(self, msg):
    print "sayMsg(" + msg + ")"
    return "say " + msg + " from " + socket.gethostbyname(socket.gethostname())

handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
transport = TSocket.TServerSocket('127.0.0.1',30303)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print "Starting python server..."
server.serve()
print "done!"

  PythonClient.py

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

from helloworld import HelloWorld
from helloworld.ttypes import *
from helloworld.constants 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('127.0.0.1', 30303)

  # 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 = HelloWorld.Client(protocol)

  # Connect!
  transport.open()

  client.ping()
  print "ping()"

  msg = client.sayHello()
  print msg
  msg = client.sayMsg(HELLO_YK)
  print msg

  transport.close()

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

 运行结果:

 

 

文件下载:

 相关文件以及测试例子代码

 

posted on 2017-10-24 23:36  禅在心中  阅读(3702)  评论(0编辑  收藏  举报