1. 程式人生 > >Thrift對多介面服務的支援

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, 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()