thrift简单使用

1. 安装

brew install thrift
pip install thrift

2. 编写thrift服务

helloworld.thrift

service HelloWorld {
    string ping(),
    string say(1:string msg)
}

3. 自动生成代码

执行以下命令:

thrift -gen py helloworld.thrift

它会在当前目录的gen目录下生成以下文件:

├── gen-py
│   ├── __init__.py
│   └── helloworld
│       ├── HelloWorld-remote
│       ├── HelloWorld.py
│       ├── __init__.py
│       ├── constants.py
│       ├── ttypes.py

4. 编写server代码

server.py

#!/usr/bin/env python 
# -*- coding: utf-8 -*-
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!"

5. 编写client代码

client.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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)


Ref

http://wangfeng7399.blog.51cto.com/3518031/1696108

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值