my_thrift.thrift
struct Message {
1: string msg
}
service MessageService {
Message getMessage(1:Message msg)
}
struct User {
1: string name
}
service UserService {
User getUser(1:User user)
}
thrift --gen py test.thrift
├── gen-py
│ ├── __init__.py
│ └── my_thrift
│ ├── constants.py
│ ├── __init__.py
│ ├── MessageService.py
│ ├── MessageService-remote
│ ├── ttypes.py
│ ├── UserService.py
│ └── UserService-remote
├── __init__.py
├── my_thrift.thrift
服务端
server.py
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
import sys
from thrift.TMultiplexedProcessor import TMultiplexedProcessor
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TTransport, TSocket
sys.path.append('./gen-py')
from my_thrift import MessageService
from my_thrift import UserService
from my_thrift.ttypes import *
class MessageHandler:
def getMessage(self, msg):
return msg
class UserHandler:
def getUser(self, user):
return user
msg_processor = MessageService.Processor(MessageHandler()) #定义msg处理器
use_processor = UserService.Processor(UserHandler()) #定义user处理器
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
processor = TMultiplexedProcessor() #使用TMultiplexedProcessor接收多个处理
processor.registerProcessor("msg", msg_processor) #注册msg服务
processor.registerProcessor("user", use_processor) #注册user服务
transport = TSocket.TServerSocket()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
server.serve() #开始监听请求
客户端
client.py
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
import sys
from thrift.protocol.TMultiplexedProtocol import TMultiplexedProtocol
sys.path.append('./gen-py')
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from my_thrift import MessageService
from my_thrift import UserService
from my_thrift.ttypes import *
transport = TSocket.TSocket()
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
msg_protocol = TMultiplexedProtocol(protocol, "msg") #如果服务端使用TMultiplexedProcessor接收处理,客户端必须用TMultiplexedProtocol并且指定serviceName和服务端的一致
user_protocol = TMultiplexedProtocol(protocol, "user")
msg_client = MessageService.Client(msg_protocol)#msg客户端
user_client = UserService.Client(user_protocol)#user客户端
transport.open()#打开链接
print msg_client.getMessage(Message(msg="111"))
print user_client.getUser(User(name="111"))
transport.close()