本文主要是介绍Thrift对多接口服务的支持,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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, TSocketsys.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 msgclass UserHandler:def getUser(self, user):return usermsg_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 TMultiplexedProtocolsys.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()
这篇关于Thrift对多接口服务的支持的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!